package com.ruicar.afs.cloud.channel.cardealer.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruicar.afs.cloud.channel.cardealer.common.Constants;
import com.ruicar.afs.cloud.channel.cardealer.common.MqTypeEnum;
import com.ruicar.afs.cloud.channel.cardealer.condition.CarDealerCondition;
import com.ruicar.afs.cloud.channel.cardealer.condition.ChangeSalesmanCondition;
import com.ruicar.afs.cloud.channel.cardealer.condition.DirectCarDealerCondition;
import com.ruicar.afs.cloud.channel.cardealer.entity.ChannelCoopeCardealerTemp;
import com.ruicar.afs.cloud.channel.cardealer.entity.CommonCarDealer;
import com.ruicar.afs.cloud.channel.cardealer.entity.DirectCarDealer;
import com.ruicar.afs.cloud.channel.cardealer.mapper.CarDealerMapper;
import com.ruicar.afs.cloud.channel.cardealer.service.CarDealerService;
import com.ruicar.afs.cloud.channel.cardealer.service.ChannelCoopeCardealerService;
import com.ruicar.afs.cloud.channel.cardealer.service.DirectCarDealerService;
import com.ruicar.afs.cloud.channel.cardealer.vo.CarDealerVo;
import com.ruicar.afs.cloud.channel.cardealer.vo.CommonCarDealerVo;
import com.ruicar.afs.cloud.channel.cardealer.vo.DirectCarDealerVo;
import com.ruicar.afs.cloud.channel.channelworkflow.entity.WorkTaskDetail;
import com.ruicar.afs.cloud.channel.channelworkflow.service.WorkTaskApproveRecordService;
import com.ruicar.afs.cloud.channel.channelworkflow.service.WorkTaskDetailService;
import com.ruicar.afs.cloud.channel.common.enums.ChannelAfsFlowEnum;
import com.ruicar.afs.cloud.channel.common.feign.ChannelUseCaseService;
import com.ruicar.afs.cloud.channel.common.mq.sender.SenderChannelToCase;
import com.ruicar.afs.cloud.channel.common.mq.sender.impl.SenderChannelToCaseImpl;
import com.ruicar.afs.cloud.channel.common.until.ChannelConfig;
import com.ruicar.afs.cloud.channel.online.condition.ChannelAccountInfoCondition;
import com.ruicar.afs.cloud.channel.online.entity.*;
import com.ruicar.afs.cloud.channel.online.feign.ApplyFeignService;
import com.ruicar.afs.cloud.channel.online.service.*;
import com.ruicar.afs.cloud.channel.online.untils.ChannelOnlineConstants;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.log.annotation.SysLog;
import com.ruicar.afs.cloud.common.core.uid.UidGenerator;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.mq.rabbit.message.AfsTransEntity;
import com.ruicar.afs.cloud.image.entity.ComAttachmentFile;
import com.ruicar.afs.cloud.image.service.ComAttachmentFileService;
import com.ruicar.afs.cloud.parameter.commom.entity.TsysAddressParam;
import com.ruicar.afs.cloud.parameter.commom.service.TsysAddressParamService;
import com.ruicar.afs.cloud.parameter.commom.utils.ParamConstants;
import com.ruicar.afs.cloud.workflow.api.dto.flowprocess.request.StartFlowRequest;
import com.ruicar.afs.cloud.workflow.gwt.service.WorkflowService;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

import static com.ruicar.afs.cloud.channel.cardealer.common.Constants.*;

/**
 * @author: sang jian
 * @date: 2020/5/14 11:01
 * @description:
 */
@RestController
@AllArgsConstructor
@RequestMapping("/carDealer")
public class CarDealerController {

    /**
     * 收款账号
     */
    @Autowired
    private ChannelAccountInfoService channelAccountInfoService;

    /**
     * 合作商车商关联
     */
    @Autowired
    private ChannelCoopeCardealerService channelCoopeCardealerService;

    /**
     * 风控数据
     */
    @Autowired
    private ChannelRiskInfoService channelRiskInfoService;

    /**
     * 保证金
     */
    @Autowired
    private ChannelQuotaInfoService channelQuotaInfoService;

    @Autowired
    private DirectCarDealerService directCarDealerService;


    @Autowired
    private CarDealerService carDealerService;
    private CarDealerMapper mapper;

    /**
     * 主营品牌
     */
    @Autowired
    private ChannelMainBrandService channelMainBrandService;

    @Autowired
    private ChannelOnlineService channelOnlineService;

    /**
     * 授权区域
     */
    @Autowired
    private ChannelAuthorizeRegionService channelAuthorizeRegionService;

    /**
     * 授权车型
     */
    @Autowired
    private ChannelAuthorizeVehicleTempService channelAuthorizeVehicleTempService;

    @Autowired
    private ApplyFeignService adminService;

    @Autowired
    private ChannelConfig channelConfig;
    @Autowired
    private ChannelUseCaseService channelUseCaseService;

    @Autowired
    private final TsysAddressParamService tsysAddressParamService;

    @Autowired
    private final WorkflowService workflowService;

    private final UidGenerator uidGenerator;

    private final WorkTaskDetailService workTaskDetailService;
    private final WorkTaskApproveRecordService workTaskApproveRecordService;
    private final ComAttachmentFileService comAttachmentFileService;

    private final SenderChannelToCaseImpl senderChannelToCaseImpl;

    private final SenderChannelToCase senderChannelToCase;


    @PostMapping("/getByCondition")
    @ApiOperation(value = "多条件分页获取普通车商")
    public IResponse getCommonCarDealerList(@RequestBody CarDealerCondition carDealerCondition) {
        Page page = new Page(carDealerCondition.getPageNumber(), carDealerCondition.getPageSize());
        IPage<CommonCarDealerVo> list = carDealerService.getCommonCarDealerList(page, carDealerCondition);
        List<CommonCarDealerVo> records = list.getRecords();
        if (records.size() > 0 && records != null) {
            for (CommonCarDealerVo dealer : records) {
                List<ChannelCoopeCardealerTemp> list1 = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                        .eq(ChannelCoopeCardealerTemp::getCardealerId, dealer.getId())
                        .eq(ChannelCoopeCardealerTemp::getCardealerType, Constants.COMMONCARDEALER)
                );
                dealer.setChannelNum(list1.size());
            }

        }
        return IResponse.success(list);
    }

    @PostMapping("/getAllCardealerName")
    @ApiOperation(value = "获取合作商下所有车商名称")
    public IResponse getAllCarDealerName(@RequestBody CarDealerCondition carDealerCondition) {

        String cardealerType = carDealerCondition.getCardealerType();
        HashSet<String> names = new HashSet<>();
        if (Constants.COMMONCARDEALER.equals(cardealerType)) {
            List<CommonCarDealer> list = carDealerService.list();
            for (CommonCarDealer carDealer : list) {
                names.add(carDealer.getCardealerName());
            }
        } else {
            List<DirectCarDealer> list = directCarDealerService.list(Wrappers.<DirectCarDealer>query().lambda().eq(DirectCarDealer::getChannelType, Constants.DIRECTCARDEALER));
            for (DirectCarDealer carDealer : list) {
                names.add(carDealer.getChannelFullName());
            }
        }
        return IResponse.success(names);
    }

    @PostMapping("/getAllCardealerNameByChannelId")
    @ApiOperation(value = "获取合作商下所有车商名称")
    public IResponse getAllCardealerNameByChannelId(@RequestBody CarDealerCondition carDealerCondition) {

        String cardealerType = carDealerCondition.getCardealerType();
        Long channelId = carDealerCondition.getChannelId();

        HashSet<String> names = new HashSet<>();
        if (Constants.COMMONCARDEALER.equals(cardealerType)) {

            List<ChannelCoopeCardealerTemp> temps = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                    .eq(ChannelCoopeCardealerTemp::getChannelId, channelId)
                    .eq(ChannelCoopeCardealerTemp::getCardealerType, Constants.COMMONCARDEALER)
            );
            if (temps.size() > 0 && temps != null) {
                for (ChannelCoopeCardealerTemp temp : temps) {
                    CommonCarDealer commonCarDealer = carDealerService.getById(temp.getCardealerId());
                    if (commonCarDealer != null) {
                        names.add(commonCarDealer.getCardealerName());
                    }
                }
            }
        } else {
            List<ChannelCoopeCardealerTemp> temps = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                    .eq(ChannelCoopeCardealerTemp::getChannelId, channelId)
                    .eq(ChannelCoopeCardealerTemp::getCardealerType, Constants.DIRECTCARDEALER)
            );
            if (temps.size() > 0 && temps != null) {
                for (ChannelCoopeCardealerTemp temp : temps) {
                    DirectCarDealer carDealer = directCarDealerService.getById(temp.getCardealerId());
                    if (carDealer != null) {
                        names.add(carDealer.getChannelFullName());
                    }
                }
            }
        }
        return IResponse.success(names);
    }


    @GetMapping("/getcommonCarDealerInfoById/{id}")
    @ApiOperation(value = "根据普通车商id获取车商信息")
    public IResponse getcommonCarDealerInfoById(@PathVariable("id") String id) {
        CommonCarDealer carDealer = carDealerService.getById(id);
        return IResponse.success(carDealer);
    }


    @GetMapping("/getChannelsByCardealerId/{id}")
    @ApiOperation(value = "根据普通车商id获取渠道信息")
    public IResponse getChannelsByCardealerId(@PathVariable("id") String id) {
        return IResponse.success(carDealerService.getChannelsByCardealerId(id));
    }

    @GetMapping("/getCommonCarDealerInDepotInfo/{socUniCrtCode}")
    @ApiOperation(value = "查普通车商是否在库")
    public IResponse getCommonCarDealerInDepotInfo(@PathVariable("socUniCrtCode") String socUniCrtCode) {
        List<CommonCarDealer> list = carDealerService.list(Wrappers.<CommonCarDealer>query().lambda()
                .eq(CommonCarDealer::getSocUniCrtCode, socUniCrtCode)
                .ne(CommonCarDealer::getStatus, Constants.DRAFT)
                .ne(CommonCarDealer::getStatus, Constants.REVIEW)
        );
        return IResponse.success(list.size());
    }


    @PostMapping("/addCarDealer")
    @ApiOperation(value = "增加普通车商")
    @Transactional(rollbackFor = Exception.class)
    public IResponse addCarDealer(@RequestBody CarDealerCondition condition) throws JsonProcessingException {

        //同步普通车商到案件服务用的
        CarDealerCondition commonCarDealerToCase = new CarDealerCondition();

        //判断是否存在这家车商
        CommonCarDealer commonCarDealer = condition.getCommonCarDealer();
        ChannelCoopeCardealerTemp temp = condition.getChannelCoopeCardealerTemp();
        String[] mainBrand = condition.getMainBrand();

        Long oldCarDealerId = null;
        String oldCode = null;
        //已停用的车商
        List<CommonCarDealer> disableCardealerlist = carDealerService.list(Wrappers.<CommonCarDealer>lambdaQuery()
                .eq(CommonCarDealer::getSocUniCrtCode, commonCarDealer.getSocUniCrtCode())
                .eq(CommonCarDealer::getStatus, Constants.DISABLE)
        );
        //所有车商
        List<CommonCarDealer> allCardealerlist = carDealerService.list(Wrappers.<CommonCarDealer>lambdaQuery()
                .eq(CommonCarDealer::getSocUniCrtCode, commonCarDealer.getSocUniCrtCode())
        );
        //所有车商
        List<CommonCarDealer> enableCardealerList = carDealerService.list(Wrappers.<CommonCarDealer>lambdaQuery()
                .eq(CommonCarDealer::getSocUniCrtCode, commonCarDealer.getSocUniCrtCode())
                .eq(CommonCarDealer::getStatus, ENABLED)
        );

        if (disableCardealerlist.size() > 0) {
            return IResponse.fail("该车商已停用!");
        }

        if (allCardealerlist.size() > 0) {
            for (CommonCarDealer carDealer : allCardealerlist) {
                List<ChannelCoopeCardealerTemp> coopeCardealerTempList = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>lambdaQuery()
                        .eq(ChannelCoopeCardealerTemp::getChannelId, temp.getChannelId())
                        .eq(ChannelCoopeCardealerTemp::getCardealerId, carDealer.getId())
                );
                if (coopeCardealerTempList.size() > 0) {
                    for (ChannelCoopeCardealerTemp coopeCardealerTemp : coopeCardealerTempList) {
                        if (Constants.DISABLE.equals(coopeCardealerTemp.getStatus())) {
                            return IResponse.fail("该车商与合作商的关系已停用!");
                        }
                    }
                    return IResponse.fail("合作商下已存在该车商!");
                }
            }
        }


        //已经存在已启用车商的情况
        if (enableCardealerList.size() > 0) {
            oldCarDealerId = enableCardealerList.get(0).getId();
            oldCode = enableCardealerList.get(0).getCardealerCode();

            //如果状态是启用就更新车商,否则就新增一条记录
            if (ENABLED.equals(commonCarDealer.getStatus())) {

                //更新附件
                List<ComAttachmentFile> fileList = comAttachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda()
                        .eq(ComAttachmentFile::getBelongNo, temp.getChannelId().toString())
                        .eq(ComAttachmentFile::getBusiNo, commonCarDealer.getId()));
                if (CollectionUtil.isNotEmpty(fileList)) {
                    for (ComAttachmentFile file : fileList) {
                        file.setBusiNo(oldCarDealerId.toString());
                    }
                    comAttachmentFileService.updateBatchById(fileList);
                }

                commonCarDealer.setId(oldCarDealerId);
                carDealerService.updateById(commonCarDealer);


            } else {
                commonCarDealer.setCardealerCode(oldCode);
                carDealerService.save(commonCarDealer);
            }
            temp.setCardealerId(commonCarDealer.getId());    //保存车商的id
            boolean result = channelCoopeCardealerService.save(temp); //更新关联表

            //更新车商主营品牌
            channelMainBrandService.remove(Wrappers.<ChannelMainBrand>query().lambda()
                    .eq(ChannelMainBrand::getChannelId, commonCarDealer.getId())
                    .eq(ChannelMainBrand::getChannelBelong, Constants.COMMONCARDEALER)
            );

            List<ChannelMainBrand> channelMainBrandList = new ArrayList<>();
            if (mainBrand != null && mainBrand.length > 0) {
                for (String main : mainBrand) {
                    ChannelMainBrand channelMainBrand = new ChannelMainBrand();
                    String code = main.split(",")[0];
                    String title = main.split(",")[1];
                    String indeterminate = main.split(",")[2];
                    String carLevel = main.split(",")[3];
                    String spellCode = main.split(",")[4];
                    channelMainBrand.setChannelId(commonCarDealer.getId());
                    channelMainBrand.setCode(code);
                    channelMainBrand.setTitle(title);
                    if (StrUtil.isNotBlank(indeterminate)) {
                        channelMainBrand.setIndeterminate(indeterminate);
                    } else {
                        channelMainBrand.setIndeterminate("false");
                    }
                    if (StrUtil.isNotBlank(spellCode)) {
                        channelMainBrand.setSpellCode(spellCode);
                    }
                    channelMainBrand.setCarLevel(carLevel);
                    channelMainBrand.setChannelBelong(Constants.COMMONCARDEALER);
                    channelMainBrandList.add(channelMainBrand);
                }
                int size = channelMainBrandList.size();
                if (size <= 1000) {
                    channelMainBrandService.saveBatch(channelMainBrandList);
                } else {
                    for (int i = 0; i < size / 1000; i++) {
                        if (size / 1000 - i > 1) {
                            channelMainBrandService.saveBatch(channelMainBrandList.subList(1000 * i, 1000 * i + 999));
                        } else {
                            channelMainBrandService.saveBatch(channelMainBrandList.subList(1000 * i, size - 1));
                        }
                    }
                }
            }

            //启用的状态走这里
            if (ENABLED.equals(temp.getStatus())) {
                List<ChannelCoopeCardealerTemp> coopes = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>lambdaQuery()
                        .eq(ChannelCoopeCardealerTemp::getCardealerId, commonCarDealer.getId())
                        .eq(ChannelCoopeCardealerTemp::getCardealerType, COMMONCARDEALER));
                commonCarDealerToCase.setChannelCoopeCardealerTemps(coopes);
                commonCarDealerToCase.setCommonCarDealer(commonCarDealer);
                commonCarDealerToCase.setChannelMainBrandList(channelMainBrandList);
                //******************同步到案件服务**************
                saveCommonCarDealerInfoToCase(commonCarDealerToCase);
            }

            //审核中的状态走这里
            if (Constants.REVIEW.equals(temp.getStatus())) {
                List<Object> workfolwList = new ArrayList<>();
                workfolwList.add(commonCarDealer);
                workfolwList.add(temp);
                commonCarDealerWorkflow(workfolwList);
            }

            return result ? IResponse.success(commonCarDealer) : IResponse.fail("保存失败");
        }

        //不存在这家车商,车商代码生成
        commonCarDealer.setCardealerCode(directCarDealerService.channelCodeSequence("commonCarDealer", "commonCarDealer", Constants.COMMONCARDEALER));
        boolean result2 = carDealerService.save(commonCarDealer);
        temp.setCardealerId(commonCarDealer.getId());
        boolean result3 = channelCoopeCardealerService.save(temp);

        //保存车商主营品牌
        List<ChannelMainBrand> channelMainBrandList = new ArrayList<>();
        if (mainBrand != null && mainBrand.length > 0) {
            for (String main : mainBrand) {
                ChannelMainBrand channelMainBrand = new ChannelMainBrand();
                String code = main.split(",")[0];
                String title = main.split(",")[1];
                String indeterminate = main.split(",")[2];
                String carLevel = main.split(",")[3];
                String spellCode = main.split(",")[4];
                channelMainBrand.setChannelId(commonCarDealer.getId());
                channelMainBrand.setCode(code);
                channelMainBrand.setTitle(title);
                if (StrUtil.isNotBlank(indeterminate)) {
                    channelMainBrand.setIndeterminate(indeterminate);
                } else {
                    channelMainBrand.setIndeterminate("false");
                }
                if (StrUtil.isNotBlank(spellCode)) {
                    channelMainBrand.setSpellCode(spellCode);
                }
                channelMainBrand.setCarLevel(carLevel);
                channelMainBrand.setChannelBelong(Constants.COMMONCARDEALER);
                channelMainBrandList.add(channelMainBrand);
            }

            int size = channelMainBrandList.size();
            if (size <= 1000) {
                channelMainBrandService.saveBatch(channelMainBrandList);
            } else {
                for (int i = 0; i < size / 1000; i++) {
                    if (size / 1000 - i > 1) {
                        channelMainBrandService.saveBatch(channelMainBrandList.subList(1000 * i, 1000 * i + 999));
                    } else {
                        channelMainBrandService.saveBatch(channelMainBrandList.subList(1000 * i, size - 1));
                    }
                }
            }
        }

        //启用的状态走这里
        if (ENABLED.equals(temp.getStatus())) {
            List<ChannelCoopeCardealerTemp> coopes = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>lambdaQuery()
                    .eq(ChannelCoopeCardealerTemp::getCardealerId, commonCarDealer.getId())
                    .eq(ChannelCoopeCardealerTemp::getCardealerType, COMMONCARDEALER));
            commonCarDealerToCase.setChannelCoopeCardealerTemps(coopes);
            commonCarDealerToCase.setCommonCarDealer(commonCarDealer);
            commonCarDealerToCase.setChannelMainBrandList(channelMainBrandList);
            //******************同步到案件服务**************
            saveCommonCarDealerInfoToCase(commonCarDealerToCase);
        }

        //审核中的状态走这里
        if (Constants.REVIEW.equals(temp.getStatus())) {
            List<Object> workfolwList = new ArrayList<>();
            workfolwList.add(commonCarDealer);
            workfolwList.add(temp);
            commonCarDealerWorkflow(workfolwList);
        }

        return result2 && result3 ? IResponse.success(commonCarDealer) : IResponse.fail("保存失败");
    }


    @PostMapping("/editCarDealer")
    @ApiOperation(value = "进件端编辑普通车商")
    @Transactional(rollbackFor = Exception.class)
    public IResponse editCarDealer(@RequestBody CarDealerCondition condition) throws JsonProcessingException {
        //同步普通车商到案件服务用的
        CarDealerCondition commonCarDealerToCase = new CarDealerCondition();
        CommonCarDealer commonCarDealer = condition.getCommonCarDealer();
        ChannelCoopeCardealerTemp temp = condition.getChannelCoopeCardealerTemp();
        String[] mainBrand = condition.getMainBrand();
        boolean result = false;

        //看一下合作商下是否有这家车商
        List<CommonCarDealer> list = carDealerService.list(Wrappers.<CommonCarDealer>lambdaQuery()
                .eq(CommonCarDealer::getSocUniCrtCode, commonCarDealer.getSocUniCrtCode())
                .ne(CommonCarDealer::getId, commonCarDealer.getId())
        );

        if (list.size() > 0) {
            for (CommonCarDealer carDealer : list) {
                List<ChannelCoopeCardealerTemp> coopeCardealerTempList = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                        .eq(ChannelCoopeCardealerTemp::getChannelId, temp.getChannelId())
                        .eq(ChannelCoopeCardealerTemp::getCardealerId, carDealer.getId())
                        .eq(ChannelCoopeCardealerTemp::getCardealerType, Constants.COMMONCARDEALER)
                );
                if (coopeCardealerTempList.size() > 0) {
                    for (ChannelCoopeCardealerTemp coopeCardealerTemp : coopeCardealerTempList) {
                        if (Constants.DISABLE.equals(coopeCardealerTemp.getStatus())) {
                            return IResponse.fail("该车商与合作商的关系已停用!");
                        }
                    }
                    return IResponse.fail("合作商下已存在该车商");
                }
            }
        }

        //同一社会码已启用的车商
        List<CommonCarDealer> list2 = carDealerService.list(Wrappers.<CommonCarDealer>lambdaQuery()
                .eq(CommonCarDealer::getSocUniCrtCode, commonCarDealer.getSocUniCrtCode())
                .eq(CommonCarDealer::getStatus, ENABLED)
                .ne(CommonCarDealer::getId, commonCarDealer.getId())
        );


        //已经存在已启用的同一个车商,合并并更新
        if (list2.size() >= 1) {
            //老id
            Long id = list2.get(0).getId();
            //草稿变成启用
            if (ENABLED.equals(commonCarDealer.getStatus())) {
                //更新附件
                List<ComAttachmentFile> fileList = comAttachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda()
                        .eq(ComAttachmentFile::getBelongNo, temp.getChannelId().toString())
                        .eq(ComAttachmentFile::getBusiNo, commonCarDealer.getId()));
                if (CollectionUtil.isNotEmpty(fileList)) {
                    for (ComAttachmentFile file : fileList) {
                        file.setBusiNo(id.toString());
                    }
                    comAttachmentFileService.updateBatchById(fileList);
                }

                //要更新品牌 删除关联表
                carDealerService.removeById(commonCarDealer.getId());
                channelMainBrandService.remove(Wrappers.<ChannelMainBrand>query().lambda()
                        .eq(ChannelMainBrand::getChannelBelong, Constants.COMMONCARDEALER)
                        .eq(ChannelMainBrand::getChannelId, commonCarDealer.getId())
                );
                channelCoopeCardealerService.remove(Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                        .eq(ChannelCoopeCardealerTemp::getCardealerId, commonCarDealer.getId())
                        .eq(ChannelCoopeCardealerTemp::getCardealerType, Constants.COMMONCARDEALER)
                        .eq(ChannelCoopeCardealerTemp::getChannelId, temp.getChannelId())
                );

                commonCarDealer.setId(id);
                result = carDealerService.updateById(commonCarDealer);


            } else {
                //草稿变成草稿
                result = carDealerService.updateById(commonCarDealer);
            }
        } else {
            result = carDealerService.updateById(commonCarDealer);
        }

        //更新车商主营品牌
        channelMainBrandService.remove(Wrappers.<ChannelMainBrand>query().lambda()
                .eq(ChannelMainBrand::getChannelId, commonCarDealer.getId())
                .eq(ChannelMainBrand::getChannelBelong, Constants.COMMONCARDEALER)
        );
        List<ChannelMainBrand> channelMainBrandList = new ArrayList<>();
        if (mainBrand != null && mainBrand.length > 0) {
            for (String main : mainBrand) {
                ChannelMainBrand channelMainBrand = new ChannelMainBrand();
                String code = main.split(",")[0];
                String title = main.split(",")[1];
                String indeterminate = main.split(",")[2];
                String carLevel = main.split(",")[3];
                String spellCode = main.split(",")[4];
                channelMainBrand.setChannelId(commonCarDealer.getId());
                channelMainBrand.setCode(code);
                channelMainBrand.setTitle(title);
                if (StrUtil.isNotBlank(indeterminate)) {
                    channelMainBrand.setIndeterminate(indeterminate);
                } else {
                    channelMainBrand.setIndeterminate("false");
                }
                if (StrUtil.isNotBlank(spellCode)) {
                    channelMainBrand.setSpellCode(spellCode);
                }
                channelMainBrand.setCarLevel(carLevel);
                channelMainBrand.setChannelBelong(Constants.COMMONCARDEALER);
                channelMainBrandList.add(channelMainBrand);
            }

            int size = channelMainBrandList.size();
            if (size <= 1000) {
                channelMainBrandService.saveBatch(channelMainBrandList);
            } else {
                for (int i = 0; i < size / 1000; i++) {
                    if (size / 1000 - i > 1) {
                        channelMainBrandService.saveBatch(channelMainBrandList.subList(1000 * i, 1000 * i + 999));
                    } else {
                        channelMainBrandService.saveBatch(channelMainBrandList.subList(1000 * i, size - 1));
                    }
                }
            }
        }

        channelCoopeCardealerService.remove(Wrappers.<ChannelCoopeCardealerTemp>lambdaQuery()
                .eq(ChannelCoopeCardealerTemp::getChannelId, temp.getChannelId())
                .eq(ChannelCoopeCardealerTemp::getCardealerId, commonCarDealer.getId())
                .eq(ChannelCoopeCardealerTemp::getCardealerType, Constants.COMMONCARDEALER));
        temp.setCardealerId(commonCarDealer.getId());
        boolean updateCoope = channelCoopeCardealerService.saveOrUpdate(temp);

        //启用的状态走这里
        if (ENABLED.equals(temp.getStatus())) {
            // commonCarDealerToCase.setChannelCoopeCardealerTemp(temp);
            List<ChannelCoopeCardealerTemp> coopes = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>lambdaQuery()
                    .eq(ChannelCoopeCardealerTemp::getCardealerId, commonCarDealer.getId())
                    .eq(ChannelCoopeCardealerTemp::getCardealerType, COMMONCARDEALER));
            commonCarDealerToCase.setChannelCoopeCardealerTemps(coopes);

            commonCarDealerToCase.setCommonCarDealer(commonCarDealer);
            commonCarDealerToCase.setChannelMainBrandList(channelMainBrandList);
            //******************同步到案件服务**************
            saveCommonCarDealerInfoToCase(commonCarDealerToCase);
        }
        //审核中的状态走这里
        if (Constants.REVIEW.equals(temp.getStatus())) {
            List<Object> workfolwList = new ArrayList<>();
            workfolwList.add(commonCarDealer);
            workfolwList.add(temp);
            commonCarDealerWorkflow(workfolwList);
        }

        return result && updateCoope ? IResponse.success(commonCarDealer) : IResponse.fail("操作失败");
    }

    @PostMapping("/editCarDealerFromChannel")
    @ApiOperation(value = "编辑普通车商")
    @Transactional(rollbackFor = Exception.class)
    public IResponse editCarDealer2(@RequestBody CarDealerCondition condition) throws JsonProcessingException {
        //同步普通车商到案件服务用的
        CarDealerCondition commonCarDealerToCase = new CarDealerCondition();
        CommonCarDealer commonCarDealer = condition.getCommonCarDealer();
        Long newId = commonCarDealer.getId();
        ChannelCoopeCardealerTemp temp = condition.getChannelCoopeCardealerTemp();
        String[] mainBrand = condition.getMainBrand();
        boolean result = false;

        //看一下合作商下是否有这家车商
        List<CommonCarDealer> list = carDealerService.list(Wrappers.<CommonCarDealer>lambdaQuery()
                .eq(CommonCarDealer::getSocUniCrtCode, commonCarDealer.getSocUniCrtCode())
                .ne(CommonCarDealer::getId, commonCarDealer.getId())
        );

        if (list.size() > 0) {
            for (CommonCarDealer carDealer : list) {
                List<ChannelCoopeCardealerTemp> coopeCardealerTempList = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                        .eq(ChannelCoopeCardealerTemp::getChannelId, temp.getChannelId())
                        .eq(ChannelCoopeCardealerTemp::getCardealerId, carDealer.getId())
                        .eq(ChannelCoopeCardealerTemp::getCardealerType, Constants.COMMONCARDEALER)
                );
                if (coopeCardealerTempList.size() > 0) {
                    for (ChannelCoopeCardealerTemp coopeCardealerTemp : coopeCardealerTempList) {
                        if (Constants.DISABLE.equals(coopeCardealerTemp.getStatus())) {
                            return IResponse.fail("该车商与合作商的关系已停用!");
                        }
                    }
                    return IResponse.fail("合作商下已存在该车商");
                }
            }
        }

        //同一社会码已启用的车商
        List<CommonCarDealer> list2 = carDealerService.list(Wrappers.<CommonCarDealer>lambdaQuery()
                .eq(CommonCarDealer::getSocUniCrtCode, commonCarDealer.getSocUniCrtCode())
                .eq(CommonCarDealer::getStatus, ENABLED)
                .ne(CommonCarDealer::getId, commonCarDealer.getId())
        );


        //已经存在已启用的同一个车商,合并并更新
        if (list2.size() >= 1) {
            //老id
            Long id = list2.get(0).getId();
            //草稿变成启用
            if (ENABLED.equals(commonCarDealer.getStatus())) {
                //更新附件
                List<ComAttachmentFile> fileList = comAttachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda()
                        .eq(ComAttachmentFile::getBelongNo, temp.getChannelId().toString())
                        .eq(ComAttachmentFile::getBusiNo, commonCarDealer.getId().toString()));
                if (CollectionUtil.isNotEmpty(fileList)) {
                    for (ComAttachmentFile file : fileList) {
                        file.setBusiNo(id.toString());
                    }
                    comAttachmentFileService.updateBatchById(fileList);
                }

                //要更新品牌 删除关联表
                carDealerService.removeById(commonCarDealer.getId());
                channelMainBrandService.remove(Wrappers.<ChannelMainBrand>query().lambda()
                        .eq(ChannelMainBrand::getChannelBelong, Constants.COMMONCARDEALER)
                        .eq(ChannelMainBrand::getChannelId, commonCarDealer.getId())
                );

                commonCarDealer.setId(id);
                result = carDealerService.updateById(commonCarDealer);

            } else {
                //草稿变成草稿
                result = carDealerService.updateById(commonCarDealer);
            }
        } else {
            result = carDealerService.updateById(commonCarDealer);
        }

        //更新车商主营品牌
        channelMainBrandService.remove(Wrappers.<ChannelMainBrand>query().lambda()
                .eq(ChannelMainBrand::getChannelId, commonCarDealer.getId())
                .eq(ChannelMainBrand::getChannelBelong, Constants.COMMONCARDEALER)
        );
        List<ChannelMainBrand> channelMainBrandList = new ArrayList<>();
        if (mainBrand != null && mainBrand.length > 0) {
            for (String main : mainBrand) {
                ChannelMainBrand channelMainBrand = new ChannelMainBrand();
                String code = main.split(",")[0];
                String title = main.split(",")[1];
                String indeterminate = main.split(",")[2];
                String carLevel = main.split(",")[3];
                String spellCode = main.split(",")[4];
                channelMainBrand.setChannelId(commonCarDealer.getId());
                channelMainBrand.setCode(code);
                channelMainBrand.setTitle(title);
                if (StrUtil.isNotBlank(indeterminate)) {
                    channelMainBrand.setIndeterminate(indeterminate);
                } else {
                    channelMainBrand.setIndeterminate("false");
                }
                if (StrUtil.isNotBlank(spellCode)) {
                    channelMainBrand.setSpellCode(spellCode);
                }
                channelMainBrand.setCarLevel(carLevel);
                channelMainBrand.setChannelBelong(Constants.COMMONCARDEALER);
                channelMainBrandList.add(channelMainBrand);
            }

            int size = channelMainBrandList.size();
            if (size <= 1000) {
                channelMainBrandService.saveBatch(channelMainBrandList);
            } else {
                for (int i = 0; i < size / 1000; i++) {
                    if (size / 1000 - i > 1) {
                        channelMainBrandService.saveBatch(channelMainBrandList.subList(1000 * i, 1000 * i + 999));
                    } else {
                        channelMainBrandService.saveBatch(channelMainBrandList.subList(1000 * i, size - 1));
                    }
                }
            }
        }

        List<ChannelCoopeCardealerTemp> oldCoope = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>lambdaQuery()
                .eq(ChannelCoopeCardealerTemp::getCardealerId, commonCarDealer.getId())
                .eq(ChannelCoopeCardealerTemp::getCardealerType, COMMONCARDEALER));

        if (CollectionUtil.isNotEmpty(oldCoope)) {
            for (ChannelCoopeCardealerTemp temp1 : oldCoope) {
                temp1.setStatus(commonCarDealer.getStatus());
                channelCoopeCardealerService.updateById(temp1);
            }
        }

        if (commonCarDealer.getId() != newId) {
            List<ChannelCoopeCardealerTemp> newCoope = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>lambdaQuery()
                    .eq(ChannelCoopeCardealerTemp::getCardealerId, newId)
                    .eq(ChannelCoopeCardealerTemp::getCardealerType, COMMONCARDEALER));
            if (CollectionUtil.isNotEmpty(newCoope)) {
                for (ChannelCoopeCardealerTemp temp1 : newCoope) {
                    temp1.setCardealerId(commonCarDealer.getId());
                    temp1.setStatus(commonCarDealer.getStatus());
                    channelCoopeCardealerService.updateById(temp1);
                }
            }
        }

        //启用的状态走这里
        if (ENABLED.equals(temp.getStatus())) {
            // commonCarDealerToCase.setChannelCoopeCardealerTemp(temp);
            List<ChannelCoopeCardealerTemp> coopes = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>lambdaQuery()
                    .eq(ChannelCoopeCardealerTemp::getCardealerId, commonCarDealer.getId())
                    .eq(ChannelCoopeCardealerTemp::getCardealerType, COMMONCARDEALER));

            commonCarDealerToCase.setChannelCoopeCardealerTemps(coopes);

            commonCarDealerToCase.setCommonCarDealer(commonCarDealer);
            commonCarDealerToCase.setChannelMainBrandList(channelMainBrandList);
            //******************同步到案件服务**************
            saveCommonCarDealerInfoToCase(commonCarDealerToCase);
        }
        //审核中的状态走这里
        if (Constants.REVIEW.equals(temp.getStatus())) {
            List<Object> workfolwList = new ArrayList<>();
            workfolwList.add(commonCarDealer);
            workfolwList.add(temp);
            commonCarDealerWorkflow(workfolwList);
        }

        return result ? IResponse.success(commonCarDealer) : IResponse.fail("操作失败");
    }


    /**
     * 普通车商提交工作流公用方法
     */
    public void commonCarDealerWorkflow(List<Object> temp) throws JsonProcessingException {
        CommonCarDealer commonCarDealer = (CommonCarDealer) temp.get(0);
        ChannelCoopeCardealerTemp coopeCardealerTemp = (ChannelCoopeCardealerTemp) temp.get(1);
        StartFlowRequest startFlow = new StartFlowRequest();
        //枚举普通车商上线
        startFlow.setAfsFlowKey(AfsEnumUtil.key(ChannelAfsFlowEnum.COMMON_CAR_DEALER));
        startFlow.setBizDataId(uidGenerator.getUID() + "");
        //枚举普通车商上线
        startFlow.setFlowName((StringUtils.isEmpty(commonCarDealer.getCardealerName()) ? "" : (commonCarDealer.getCardealerName()) + "-") + AfsEnumUtil.desc(ChannelAfsFlowEnum.COMMON_CAR_DEALER));

        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(commonCarDealer);
        JSONObject cancelJson = JSONObject.parseObject(json);
        workflowService.startWorkFlow(startFlow, cancelJson);

        //保存业务相关数据、用户前端逻辑判断
        WorkTaskDetail detail = new WorkTaskDetail();
        detail.setBizDataId(startFlow.getBizDataId());

        detail.setName(commonCarDealer.getCardealerName());
        detail.setFlowName(AfsEnumUtil.desc(ChannelAfsFlowEnum.COMMON_CAR_DEALER));
        //车商,渠道id绑定
        detail.setBusinessKey(commonCarDealer.getId());
        detail.setChannelId(coopeCardealerTemp.getChannelId());
        workTaskDetailService.save(detail);
        workTaskApproveRecordService.startSave(AfsEnumUtil.desc(ChannelAfsFlowEnum.COMMON_CAR_DEALER), startFlow.getBizDataId());

    }


    /**
     * 直营车商提交工作流公用方法
     */
    public void directCarDealerWorkflow(List<Object> temp) throws JsonProcessingException {

        DirectCarDealer directCarDealer = (DirectCarDealer) temp.get(0);
        ChannelCoopeCardealerTemp coopeCardealerTemp = (ChannelCoopeCardealerTemp) temp.get(1);

        //如果关联的合作商打款类型为车商,将车商收款账号状态改成01
        Long channelId = coopeCardealerTemp.getChannelId();
        ChannelBaseInfoTemp baseInfoTemp = channelOnlineService.getById(channelId);
        if (Constants.CAR_DEALER.equals(baseInfoTemp.getPaymentObject())) {
            List<ChannelReceivablesAccountTemp> draftAccount = channelAccountInfoService.list(Wrappers.<ChannelReceivablesAccountTemp>query().lambda()
                    .eq(ChannelReceivablesAccountTemp::getChannelId, directCarDealer.getId())
                    .eq(ChannelReceivablesAccountTemp::getStatus, Constants.DRAFT)
            );

            if (draftAccount.size() > 0) {
                for (ChannelReceivablesAccountTemp accountTemp : draftAccount) {
                    accountTemp.setStatus(Constants.REVIEW);
                    channelAccountInfoService.updateById(accountTemp);
                }
            }

        }

        StartFlowRequest startFlow = new StartFlowRequest();
        //枚举直营车商上线
        startFlow.setAfsFlowKey(AfsEnumUtil.key(ChannelAfsFlowEnum.DIRECT_CAR_DEALER));
        startFlow.setBizDataId(uidGenerator.getUID() + "");
        //枚举直营车商上线
        startFlow.setFlowName((StringUtils.isEmpty(directCarDealer.getChannelFullName()) ? "" : (directCarDealer.getChannelFullName()) + "-") + AfsEnumUtil.desc(ChannelAfsFlowEnum.DIRECT_CAR_DEALER));

        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(directCarDealer);
        JSONObject cancelJson = JSONObject.parseObject(json);
        cancelJson.put(AfsEnumUtil.key(ChannelAfsFlowEnum.PAYMENT_OBJECT), baseInfoTemp.getPaymentObject());
        workflowService.startWorkFlow(startFlow, cancelJson);

        //保存业务相关数据、用户前端逻辑判断
        WorkTaskDetail detail = new WorkTaskDetail();
        detail.setBizDataId(startFlow.getBizDataId());

        detail.setName(directCarDealer.getChannelFullName());
        detail.setFlowName(AfsEnumUtil.desc(ChannelAfsFlowEnum.DIRECT_CAR_DEALER));
        //车商,渠道id绑定
        detail.setBusinessKey(directCarDealer.getId());
        detail.setChannelId(coopeCardealerTemp.getChannelId());
        workTaskDetailService.save(detail);
        workTaskApproveRecordService.startSave(AfsEnumUtil.desc(ChannelAfsFlowEnum.DIRECT_CAR_DEALER), startFlow.getBizDataId());

    }


    @GetMapping("/disableCarDealer/{ids}")
    @ApiOperation(value = "停用普通车商")
    @Transactional(rollbackFor = Exception.class)
    public IResponse diableCarDealer(@PathVariable String[] ids) {
        if (ids == null) {
            return IResponse.fail("参数为空");
        }
        for (int i = 0; i < ids.length; i++) {
            CommonCarDealer commonCarDealer = carDealerService.getById(ids[i]);
            commonCarDealer.setStatus(Constants.DISABLE);
            boolean update = carDealerService.updateById(commonCarDealer);
            if (!update) {
                return IResponse.fail("操作失败");
            }
            //更新中间表
            List<ChannelCoopeCardealerTemp> coopeCardealers = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                    .eq(ChannelCoopeCardealerTemp::getCardealerId, ids[i])
                    .eq(ChannelCoopeCardealerTemp::getCardealerType, Constants.COMMONCARDEALER));
            if (coopeCardealers != null && coopeCardealers.size() > 0) {
                if (coopeCardealers != null && coopeCardealers.size() > 0) {
                    for (ChannelCoopeCardealerTemp coopeCardealer : coopeCardealers) {
                        coopeCardealer.setStatus(Constants.DISABLE);
                    }
                }
                boolean update2 = channelCoopeCardealerService.updateBatchById(coopeCardealers);
                if (!update) {
                    return IResponse.fail("停用失败");
                }
            }
        }
        return IResponse.success("停用成功");
    }

    @GetMapping("/bulkEditingSalesman/{salesman}/{ids}")
    @ApiOperation(value = "批量修改业务员")
    public IResponse bulkEditingSalesman(@PathVariable String salesman, @PathVariable String[] ids) {
        if (ids == null || salesman == null) {
            return IResponse.fail("参数为空").setData(null);
        }
        for (int i = 0; i < ids.length; i++) {
            CommonCarDealer carDealer = carDealerService.getById(ids[i]);
            carDealer.setSalesMan(salesman);
            boolean result = carDealerService.updateById(carDealer);
            List<ChannelCoopeCardealerTemp> list = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                    .eq(ChannelCoopeCardealerTemp::getCardealerId, ids[i])
                    .eq(ChannelCoopeCardealerTemp::getCardealerType, Constants.COMMONCARDEALER)
            );
            if (list.size() > 0 && list != null) {
                for (ChannelCoopeCardealerTemp temp : list) {
                    temp.setAssociAccount(salesman);
                }
            }
            boolean result2 = channelCoopeCardealerService.updateBatchById(list);
            if (!result || !result2) {
                return IResponse.fail("修改失败");
            }
        }
        return IResponse.success("修改成功");
    }


    @DeleteMapping("/delByIds/{channelId}/{id}")
    @ApiOperation(value = "删除车商")
    public IResponse deleteCardealerById(@PathVariable String channelId, @PathVariable String id) {
        List<ChannelCoopeCardealerTemp> list = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                .eq(StringUtils.isNotEmpty(channelId), ChannelCoopeCardealerTemp::getChannelId, channelId)
                .eq(ChannelCoopeCardealerTemp::getCardealerId, id)
        );
        boolean b = directCarDealerService.removeById(id);
        if (list != null && list.size() > 0) {
            for (ChannelCoopeCardealerTemp temp : list) {
                boolean result = channelCoopeCardealerService.removeById(temp.getId());
                if (!result) {
                    return IResponse.fail("删除失败");
                }
            }
        }
        return IResponse.success("删除成功");
    }

    @DeleteMapping("/deleteCommonCardealerById/{id}")
    @ApiOperation(value = "删除普通车商")
    public IResponse deleteCommonCardealerById(@PathVariable String id) {
        //删车商
        carDealerService.removeById(id);
        //删关联表
        channelCoopeCardealerService.remove(Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                .eq(ChannelCoopeCardealerTemp::getCardealerId, id)
                .eq(ChannelCoopeCardealerTemp::getCardealerType, Constants.COMMONCARDEALER)
        );
        return IResponse.success("删除成功");
    }


    @GetMapping("/CarDealListForZY")
    @ApiOperation(value = "根据合作商账户返回此账户下的车商列表信息")
    public IResponse<CarDealerVo> getCarDealersByUserId(@RequestParam(value = "userId") String userId, @RequestParam("cardealerType") String cardealerType) {
        if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(cardealerType)) {
            return IResponse.fail("查询参数为空").setData(null);
        }

        return carDealerService.getCarDealersByUserId(userId, cardealerType);
    }


    @GetMapping("/disableDirectCarDealer/{ids}")
    @ApiOperation(value = "禁用直营车商")
    public IResponse disableDirectCarDealer(@PathVariable String[] ids) {
        if (ids == null) {
            return IResponse.fail("参数为空").setData(null);
        }
        for (int i = 0; i < ids.length; i++) {
            DirectCarDealer dealer = directCarDealerService.getById(ids[i]);
            if (dealer.getChannelStatusOldCar() != null) {
                dealer.setChannelStatusOldCar(Constants.DISABLE);
            }
            if (dealer.getChannelStatus() != null) {
                dealer.setChannelStatus(Constants.DISABLE);
            }
            List<ChannelCoopeCardealerTemp> coopeCardealerTempList = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                    .eq(ChannelCoopeCardealerTemp::getCardealerId, ids[i])
                    .eq(ChannelCoopeCardealerTemp::getCardealerType, Constants.DIRECTCARDEALER)
            );
            if (coopeCardealerTempList.size() > 0 && coopeCardealerTempList != null) {
                for (ChannelCoopeCardealerTemp temp : coopeCardealerTempList) {
                    temp.setStatus(Constants.DISABLE);
                    channelCoopeCardealerService.updateById(temp);
                }
            }
            boolean result = directCarDealerService.updateById(dealer);
            if (!result) {
                return IResponse.fail("第" + (i + 1) + "车商停用失败");
            }
        }
        return IResponse.success("禁用成功");
    }

    @GetMapping("/disableDirectCarDealerFromApply/{ids}/{channelId}/{status}")
    @ApiOperation(value = "禁用进件端直营车商")
    public IResponse disableDirectCarDealerFromApply(@PathVariable String[] ids, @PathVariable String channelId, @PathVariable String status) {
        if (ids == null || channelId == null) {
            return IResponse.fail("参数为空").setData(null);
        }
        boolean result = true;
        for (int i = 0; i < ids.length; i++) {
            List<ChannelCoopeCardealerTemp> coopeCardealerTempList = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                    .eq(ChannelCoopeCardealerTemp::getCardealerId, ids[i])
                    .eq(ChannelCoopeCardealerTemp::getCardealerType, Constants.DIRECTCARDEALER)
                    .eq(ChannelCoopeCardealerTemp::getChannelId, channelId)
            );
            if (coopeCardealerTempList.size() > 0 && coopeCardealerTempList != null) {
                for (ChannelCoopeCardealerTemp temp : coopeCardealerTempList) {
                    temp.setStatus(status);
                    result = channelCoopeCardealerService.updateById(temp);
                    if (!result) {
                        return IResponse.fail("第" + (i + 1) + "车商停用失败");
                    }

                }
            }
        }
        //停用案件端直营车商
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("clientId", channelConfig.getCaseClientId());
        headers.put("clientSecret", channelConfig.getCaseClientSecret());
        Assert.isTrue((boolean) channelUseCaseService.disableDirectCarDealerFromApply(ids, channelId, status, headers).getData(), "操作失败,请重试!");
        return IResponse.success("禁用成功");
    }

    @DeleteMapping("/deleteDirectCardealerByIdFromApply/{channelId}/{id}")
    @ApiOperation(value = "删除进件端直营车商")
    public IResponse deleteDirectCardealerByIdFromApply(@PathVariable String channelId, @PathVariable String id) {
        List<ChannelCoopeCardealerTemp> list = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                .eq(StringUtils.isNotEmpty(channelId), ChannelCoopeCardealerTemp::getChannelId, channelId)
                .eq(ChannelCoopeCardealerTemp::getCardealerId, id)
                .eq(ChannelCoopeCardealerTemp::getCardealerType, Constants.DIRECTCARDEALER)
        );
        if (list != null && list.size() > 0) {
            for (ChannelCoopeCardealerTemp temp : list) {
                boolean result = channelCoopeCardealerService.removeById(temp.getId());
                if (!result) {
                    return IResponse.fail("删除失败");
                }
            }
        }
        return IResponse.success("删除成功");
    }


    @PostMapping("/getDirectCarDealerListByCondition")
    @ApiOperation(value = "多条件分页获取直营车商")
    public IResponse<IPage<DirectCarDealerVo>> getDirectCarDealerList(@RequestBody CarDealerCondition carDealerCondition) {
        Page page = new Page(carDealerCondition.getPageNumber(), carDealerCondition.getPageSize());
        IPage<DirectCarDealerVo> list = carDealerService.getDirectCarDealerList(page, carDealerCondition);
        List<DirectCarDealerVo> records = list.getRecords();
        if (records.size() > 0 && records != null) {
            for (DirectCarDealerVo dealer : records) {
                List<ChannelCoopeCardealerTemp> list1 = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                        .eq(ChannelCoopeCardealerTemp::getCardealerId, dealer.getId())
                        .eq(ChannelCoopeCardealerTemp::getCardealerType, Constants.DIRECTCARDEALER)
                );
                dealer.setChannelNum(list1.size());
            }
        }
        return IResponse.success(list);
    }

    @PostMapping("/checkCooper")
    @ApiOperation(value = "验证直营车商和合作商之间的关系")
    public IResponse checkCooper(@RequestBody DirectCarDealerCondition condition) {

        String channelId = condition.getChannelId();
        String socUniCrtCode = condition.getSocUniCrtCode();
        Long cardealerId = null;

        List<DirectCarDealer> resultList = directCarDealerService.list(Wrappers.<DirectCarDealer>query().lambda()
                .eq(DirectCarDealer::getSocUniCrtCode, socUniCrtCode)
                .eq(DirectCarDealer::getChannelType, Constants.DIRECTCARDEALER));
        if (resultList.size() > 0 && resultList != null) {
            cardealerId = resultList.get(0).getId();
        } else {
            return IResponse.success("01");
        }
        List<ChannelCoopeCardealerTemp> temps = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                .eq(ChannelCoopeCardealerTemp::getChannelId, channelId)
                .eq(ChannelCoopeCardealerTemp::getCardealerId, cardealerId)
                .eq(ChannelCoopeCardealerTemp::getCardealerType, Constants.DIRECTCARDEALER)
        );
        if (temps != null && temps.size() > 0) {
            return IResponse.success("00");
        }
        return IResponse.success("01");

    }


    @RequestMapping(value = "/saveDirectCarDealer", method = RequestMethod.POST)
    @ApiOperation(value = "保存直营车商申请信息")
    @SysLog("保存直营车商申请信息")
    @Transactional(rollbackFor = Exception.class)
    public IResponse saveDirectCarDealer(@RequestBody DirectCarDealerCondition condition) throws JsonProcessingException {


        //推送到案件的数据
        DirectCarDealerCondition directCarDealerConditionToCase = new DirectCarDealerCondition();

        List<ChannelRiskInfoTemp> channelRiskInfoTempListToCase = new ArrayList<>();
        ArrayList<ChannelQuotaInfoTemp> channelQuotaInfoTempsToCase = new ArrayList<>();
        ArrayList<ChannelAuthorizeVehicleTemp> ChannelAuthorizeVehicleTempsToCase = new ArrayList<>();
        ArrayList<ChannelAuthorizeRegionTemp> ChannelAuthorizeRegionTempsToCase = new ArrayList<>();


        List list = new ArrayList<>();
        //从前端传来的数据中拿到直营车商的基本信息
        DirectCarDealer temp = condition.getChannelBaseInfoTemp();
        //从前端传来的数据中拿到中间表信息
        ChannelCoopeCardealerTemp channelCoopeCardealerTemp = condition.getChannelCoopeCardealerTemp();
        //风控信息
        ChannelRiskInfoTemp channelRiskInfoTemp = condition.getChannelRiskInfoTemp();
        //保证金信息
        List<ChannelQuotaInfoTemp> channelQuotaInfoList = condition.getChannelQuotaInfoTempList();
        /** 保存渠道二手车风控信息*/
        ChannelRiskInfoTemp channelRiskInfoTempOld = condition.getChannelRiskInfoTempOld();
        //二手车保证金
        List<ChannelQuotaInfoTemp> channelQuotaInfoListOld = condition.getChannelQuotaInfoTempOldList();
        //主营品牌
        String[] mainBrand = condition.getMainBrand();

        //新车授权区域
        String[] mainArea = condition.getMainArea();
        //二手车授权区域
        String[] mainAreaOld = condition.getMainAreaOld();
        //授权车型
        String[] mainCar = condition.getMainCar();
        //二手车授权车型
        String[] mainCarOld = condition.getMainCarOld();

        //省市地址
        String[] channelAdminAddressValue = condition.getChannelAdminAddressValue();
        String[] channelAddressValue = condition.getChannelAddressValue();

        if (channelAdminAddressValue != null && channelAdminAddressValue.length > 0) {
            temp.setChannelAdminProvince(channelAdminAddressValue[0]);
            temp.setChannelAdminCity(channelAdminAddressValue[1]);
        }
        if (channelAddressValue != null && channelAddressValue.length > 0) {
            temp.setChannelProvince(channelAddressValue[0]);
            temp.setChannelCity(channelAddressValue[1]);
        }

        //根据统一社会信用码判断是否已存在已启用这家车商
        List<DirectCarDealer> enableDealerList = directCarDealerService.list(Wrappers.<DirectCarDealer>query().lambda()
                .eq(DirectCarDealer::getSocUniCrtCode, temp.getSocUniCrtCode())
                .eq(DirectCarDealer::getChannelType, temp.getChannelType())
                .and(wrapper1 -> wrapper1.eq(DirectCarDealer::getChannelStatusOldCar, ENABLED)
                        .or(wrapper2 -> wrapper2.eq(DirectCarDealer::getChannelStatus, ENABLED))
                )
        );

        //停用的车商
        List<DirectCarDealer> disableDealerList = directCarDealerService.list(Wrappers.<DirectCarDealer>query().lambda()
                .eq(DirectCarDealer::getSocUniCrtCode, temp.getSocUniCrtCode())
                .eq(DirectCarDealer::getChannelType, temp.getChannelType())
                .and(wrapper1 -> wrapper1.eq(DirectCarDealer::getChannelStatusOldCar, Constants.DISABLE)
                        .or(wrapper2 -> wrapper2.eq(DirectCarDealer::getChannelStatus, Constants.DISABLE))
                )
        );

        List<DirectCarDealer> allDealerList = directCarDealerService.list(Wrappers.<DirectCarDealer>query().lambda()
                .eq(DirectCarDealer::getSocUniCrtCode, temp.getSocUniCrtCode())
                .eq(DirectCarDealer::getChannelType, temp.getChannelType())
        );
        //判断车商是否停用
        if (disableDealerList.size() > 0) {
            return IResponse.fail("该车商已停用");
        }

        //判断合作商是否存在这家车商
        if (allDealerList.size() > 0) {
            for (DirectCarDealer dealer : allDealerList) {
                List<ChannelCoopeCardealerTemp> coopeCardealerTemps = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                        .eq(ChannelCoopeCardealerTemp::getCardealerId, dealer.getId())
                        .eq(ChannelCoopeCardealerTemp::getChannelId, channelCoopeCardealerTemp.getChannelId())
                );
                if (coopeCardealerTemps.size() > 0) {
                    return IResponse.fail("该合作商已建立与该车商合作关系!");
                }
            }
        }

        if (enableDealerList.size() > 0) {
            //拿到已启用的车商id
            Long carDealerId = null;
            String oldCarDealerCode = null;
            for (DirectCarDealer temp1 : enableDealerList) {
                carDealerId = temp1.getId();
                oldCarDealerCode = temp1.getChannelCode();
            }

            //判断新加的车商是否是草稿,如果状态是启用就更新车商,否则就新增一条记录
            if (ENABLED.equals(temp.getChannelStatus()) || ENABLED.equals(temp.getChannelStatusOldCar())) {
                boolean newCar = enableDealerList.get(0).getChannelStatus() != null && enableDealerList.get(0).getChannelStatus() != "";
                boolean oldCar = enableDealerList.get(0).getChannelStatusOldCar() != null && enableDealerList.get(0).getChannelStatusOldCar() != "";
                if (newCar) {
                    temp.setChannelStatus(ENABLED);
                }
                if (oldCar) {
                    temp.setChannelStatusOldCar(ENABLED);
                }
                if (newCar && oldCar) {
                    temp.setBusinessType(Constants.BUSINESS_TYPE_NEW_CAR + "," + Constants.BUSINESS_TYPE_OLD_CAR);
                } else if (newCar && !oldCar) {
                    temp.setBusinessType(Constants.BUSINESS_TYPE_NEW_CAR);
                } else if (!newCar && oldCar) {
                    temp.setBusinessType(Constants.BUSINESS_TYPE_OLD_CAR);
                }

                //更新附件
                List<ComAttachmentFile> fileList = comAttachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda()
                        .eq(ComAttachmentFile::getBelongNo, channelCoopeCardealerTemp.getChannelId().toString())
                        .eq(ComAttachmentFile::getBusiNo, temp.getId()));
                if (CollectionUtil.isNotEmpty(fileList)) {
                    for (ComAttachmentFile file : fileList) {
                        file.setBusiNo(carDealerId.toString());
                    }
                    comAttachmentFileService.updateBatchById(fileList);
                }

                temp.setId(carDealerId);

                directCarDealerService.updateById(temp);
            } else {
                temp.setChannelCode(oldCarDealerCode);
                directCarDealerService.save(temp);
            }

            list.add(temp);
            //保存到中间表
            channelCoopeCardealerTemp.setCardealerId(temp.getId());
            channelCoopeCardealerService.save(channelCoopeCardealerTemp);
            list.add(channelCoopeCardealerTemp);
            directCarDealerConditionToCase.setChannelBaseInfoTemp(temp);
            directCarDealerConditionToCase.setChannelCoopeCardealerTemp(channelCoopeCardealerTemp);

            //更新车商主营品牌
            channelMainBrandService.remove(Wrappers.<ChannelMainBrand>query().lambda()
                    .eq(ChannelMainBrand::getChannelId, temp.getId())
                    .eq(ChannelMainBrand::getChannelBelong, Constants.DIRECTCARDEALER)
            );
            //更新主营品牌
            List<ChannelMainBrand> channelMainBrandList = new ArrayList<>();
            if (mainBrand != null && mainBrand.length > 0) {
                for (String main : mainBrand) {
                    ChannelMainBrand channelMainBrand = new ChannelMainBrand();
                    String code = main.split(",")[0];
                    String title = main.split(",")[1];
                    String indeterminate = main.split(",")[2];
                    String carLevel = main.split(",")[3];
                    String spellCode = main.split(",")[4];
                    channelMainBrand.setChannelId(temp.getId());
                    channelMainBrand.setCode(code);
                    channelMainBrand.setTitle(title);
                    if (StrUtil.isNotBlank(indeterminate)) {
                        channelMainBrand.setIndeterminate(indeterminate);
                    } else {
                        channelMainBrand.setIndeterminate("false");
                    }
                    if (StrUtil.isNotBlank(spellCode)) {
                        channelMainBrand.setSpellCode(spellCode);
                    }
                    channelMainBrand.setCarLevel(carLevel);
                    channelMainBrand.setChannelBelong(Constants.DIRECTCARDEALER);
                    channelMainBrandList.add(channelMainBrand);
                }
                //   channelMainBrandService.saveOrUpdateBatch(channelMainBrandList);

                int size = channelMainBrandList.size();
                if (size <= 1000) {
                    channelMainBrandService.saveBatch(channelMainBrandList);
                } else {
                    for (int i = 0; i < size / 1000; i++) {
                        if (size / 1000 - i > 1) {
                            channelMainBrandService.saveBatch(channelMainBrandList.subList(1000 * i, 1000 * i + 999));
                        } else {
                            channelMainBrandService.saveBatch(channelMainBrandList.subList(1000 * i, size - 1));
                        }
                    }
                }
            }
            directCarDealerConditionToCase.setMainBrandList(channelMainBrandList);

            /** 更新车商风控信息*/
            //判断当前登陆者是否拥有新车权限，由前端传入
            if (ChannelOnlineConstants.IS_HAVE_CAR_ROLE_YES.equals(condition.getIsNewCarRole())) {
                /** 保存渠道新车风控信息*/
                //渠道id赋值
                channelRiskInfoTemp.setChannelId(temp.getId());
                //清楚旧数据
                channelRiskInfoService.remove(Wrappers.<ChannelRiskInfoTemp>query().lambda()
                        .eq(ChannelRiskInfoTemp::getChannelId, temp.getId())
                        .eq(ChannelRiskInfoTemp::getBusinessType, Constants.BUSINESS_TYPE_NEW_CAR));
                channelRiskInfoService.saveOrUpdate(channelRiskInfoTemp);
                channelRiskInfoTempListToCase.add(channelRiskInfoTemp);

                /** 保存新车保证金信息前先清除旧的数据*/
                channelQuotaInfoService.remove(Wrappers.<ChannelQuotaInfoTemp>query().lambda()
                        .eq(ChannelQuotaInfoTemp::getChannelId, temp.getId())
                        .eq(ChannelQuotaInfoTemp::getBusinessType, Constants.BUSINESS_TYPE_NEW_CAR));
                //保存新车保证金信息
                for (ChannelQuotaInfoTemp quotaInfo : channelQuotaInfoList) {
                    quotaInfo.setChannelId(temp.getId());
                    //临时额度
                    BigDecimal tempQuota = quotaInfo.getTempQuota() == null ? BigDecimal.ZERO : quotaInfo.getTempQuota();
                    //签放额度
                    BigDecimal quotaSigning = quotaInfo.getQuotaAmount() == null ? BigDecimal.ZERO : quotaInfo.getQuotaAmount();
                    //剩余额度 = 临时额度+签放额度
                    quotaInfo.setSurplusQuota(tempQuota.add(quotaSigning));
                    //占用额度为0
                    quotaInfo.setOccupiedQuota(BigDecimal.ZERO);
                    channelQuotaInfoService.saveOrUpdate(quotaInfo);
                    channelQuotaInfoTempsToCase.add(quotaInfo);
                }

                /** 保存渠道新车授权区域信息前先清除旧的数据*/
                channelAuthorizeRegionService.remove(Wrappers.<ChannelAuthorizeRegionTemp>query().lambda()
                        .eq(ChannelAuthorizeRegionTemp::getChannelId, temp.getId())
                        .eq(ChannelAuthorizeRegionTemp::getBusinessType, Constants.BUSINESS_TYPE_NEW_CAR));
                //保存渠道新车授权区域
                List<ChannelAuthorizeRegionTemp> channelAuthorizeRegionTempList = new ArrayList<>();
                if (mainArea != null && mainArea.length > 0) {
                    for (String area : mainArea) {
                        ChannelAuthorizeRegionTemp regionTemp = new ChannelAuthorizeRegionTemp();
                        String code = area.split(",")[0];
                        String title = area.split(",")[1];
                        String isParent = area.split(",")[2];
                        String parentId = area.split(",")[3];
                        regionTemp.setChannelId(temp.getId());
                        regionTemp.setCode(code);
                        regionTemp.setTitle(title);
                        regionTemp.setIsParent(isParent);
                        regionTemp.setParentId(parentId);
                        regionTemp.setBusinessType(Constants.BUSINESS_TYPE_NEW_CAR);
                        channelAuthorizeRegionTempList.add(regionTemp);
                    }
                    int size = channelAuthorizeRegionTempList.size();
                    if (size <= 1000) {
                        channelAuthorizeRegionService.saveOrUpdateBatch(channelAuthorizeRegionTempList);
                    } else {
                        for (int i = 0; i < size / 1000; i++) {
                            if (size / 1000 - i > 1) {
                                channelAuthorizeRegionService.saveOrUpdateBatch(channelAuthorizeRegionTempList.subList(1000 * i, 1000 * i + 999));
                            } else {
                                channelAuthorizeRegionService.saveOrUpdateBatch(channelAuthorizeRegionTempList.subList(1000 * i, size - 1));
                            }
                        }
                    }
                    ChannelAuthorizeRegionTempsToCase.addAll(channelAuthorizeRegionTempList);
                }

                /** 保存渠道授权车型信息前先清除旧的数据*/
                channelAuthorizeVehicleTempService.remove(Wrappers.<ChannelAuthorizeVehicleTemp>query().lambda()
                        .eq(ChannelAuthorizeVehicleTemp::getChannelId, temp.getId())
                        .eq(ChannelAuthorizeVehicleTemp::getBusinessType, Constants.BUSINESS_TYPE_NEW_CAR));
                //保存渠道新车授权车型
                List<ChannelAuthorizeVehicleTemp> channelAuthorizeVehicleList = new ArrayList<>();
                if (mainCar != null && mainCar.length > 0) {
                    for (String main : mainCar) {
                        ChannelAuthorizeVehicleTemp channelAuthorizeVehicleTemp = new ChannelAuthorizeVehicleTemp();
                        String code = main.split(",")[0];
                        String title = main.split(",")[1];
                        String indeterminate = main.split(",")[3];
                        String carLevel = main.split(",")[4];
                        String spellCode = main.split(",")[5];
                        String carType = main.split(",")[6];
                        String parentId = main.split(",")[2];
                        channelAuthorizeVehicleTemp.setChannelId(temp.getId());
                        channelAuthorizeVehicleTemp.setCode(code);
                        channelAuthorizeVehicleTemp.setTitle(title);
                        channelAuthorizeVehicleTemp.setParentId(parentId);
                        channelAuthorizeVehicleTemp.setCarLevel(carLevel);
                         if("null".equals(carType)){
                        channelAuthorizeVehicleTemp.setCarType("");
                    }else{
                        channelAuthorizeVehicleTemp.setCarType(carType);
                    }
                        if (StrUtil.isNotBlank(indeterminate)) {
                            channelAuthorizeVehicleTemp.setIndeterminate(indeterminate);
                        } else {
                            channelAuthorizeVehicleTemp.setIndeterminate("false");
                        }
                        if (StrUtil.isNotBlank(spellCode)) {
                            channelAuthorizeVehicleTemp.setSpellCode(spellCode);
                        }
                        channelAuthorizeVehicleTemp.setBusinessType(Constants.BUSINESS_TYPE_NEW_CAR);
                        channelAuthorizeVehicleList.add(channelAuthorizeVehicleTemp);
                    }
                    int size = channelAuthorizeVehicleList.size();
                    if (size <= 1000) {
                        channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList);
                    } else {
                        for (int i = 0; i < size / 1000; i++) {
                            if (size / 1000 - i > 1) {
                                channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList.subList(1000 * i, 1000 * i + 999));
                            } else {
                                channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList.subList(1000 * i, size - 1));
                            }
                        }
                    }
                    ChannelAuthorizeVehicleTempsToCase.addAll(channelAuthorizeVehicleList);
                }
            }


            //判断当前登陆者是否拥有二手车权限，由前端传入
            if (ChannelOnlineConstants.IS_HAVE_CAR_ROLE_YES.equals(condition.getIsOldCarRole())) {
                //渠道id赋值
                channelRiskInfoTempOld.setChannelId(temp.getId());
                //二手车风控信息查询判断
                channelRiskInfoService.remove(Wrappers.<ChannelRiskInfoTemp>query().lambda()
                        .eq(ChannelRiskInfoTemp::getChannelId, temp.getId())
                        .eq(ChannelRiskInfoTemp::getBusinessType, Constants.BUSINESS_TYPE_OLD_CAR));
                channelRiskInfoService.saveOrUpdate(channelRiskInfoTempOld);
                channelRiskInfoTempListToCase.add(channelRiskInfoTempOld);

                list.add(channelRiskInfoTemp);

                /** 保存渠道二手车保证金信息前先清除旧的数据*/
                channelQuotaInfoService.remove(Wrappers.<ChannelQuotaInfoTemp>query().lambda()
                        .eq(ChannelQuotaInfoTemp::getChannelId, temp.getId())
                        .eq(ChannelQuotaInfoTemp::getBusinessType, Constants.BUSINESS_TYPE_OLD_CAR));
                //保存二手车保证金信息
                for (ChannelQuotaInfoTemp quotaInfo : channelQuotaInfoListOld) {
                    quotaInfo.setChannelId(temp.getId());
                    //临时额度
                    BigDecimal tempQuota = quotaInfo.getTempQuota() == null ? BigDecimal.ZERO : quotaInfo.getTempQuota();
                    //签放额度
                    BigDecimal quotaSigning = quotaInfo.getQuotaAmount() == null ? BigDecimal.ZERO : quotaInfo.getQuotaAmount();
                    //剩余额度 = 临时额度+签放额度
                    quotaInfo.setSurplusQuota(tempQuota.add(quotaSigning));
                    //占用额度为0
                    quotaInfo.setOccupiedQuota(BigDecimal.ZERO);

                    channelQuotaInfoService.saveOrUpdate(quotaInfo);
                    channelQuotaInfoTempsToCase.add(quotaInfo);
                }

                /** 保存渠道二手车授权区域信息前先清除旧的数据*/
                channelAuthorizeRegionService.remove(Wrappers.<ChannelAuthorizeRegionTemp>query().lambda()
                        .eq(ChannelAuthorizeRegionTemp::getChannelId, temp.getId())
                        .eq(ChannelAuthorizeRegionTemp::getBusinessType, Constants.BUSINESS_TYPE_OLD_CAR));
                //保存渠道二手车授权区域
                List<ChannelAuthorizeRegionTemp> channelAuthorizeRegionTempList = new ArrayList<>();
                if (mainAreaOld != null && mainAreaOld.length > 0) {
                    for (String area : mainAreaOld) {
                        ChannelAuthorizeRegionTemp regionTemp = new ChannelAuthorizeRegionTemp();
                        String code = area.split(",")[0];
                        String title = area.split(",")[1];
                        String isParent = area.split(",")[2];
                        String parentId = area.split(",")[3];
                        regionTemp.setChannelId(temp.getId());
                        regionTemp.setCode(code);
                        regionTemp.setTitle(title);
                        regionTemp.setIsParent(isParent);
                        regionTemp.setParentId(parentId);
                        regionTemp.setBusinessType(Constants.BUSINESS_TYPE_OLD_CAR);
                        channelAuthorizeRegionTempList.add(regionTemp);
                    }

                    int size = channelAuthorizeRegionTempList.size();
                    if (size <= 1000) {
                        channelAuthorizeRegionService.saveBatch(channelAuthorizeRegionTempList);
                    } else {
                        for (int i = 0; i < size / 1000; i++) {
                            if (size / 1000 - i > 1) {
                                channelAuthorizeRegionService.saveBatch(channelAuthorizeRegionTempList.subList(1000 * i, 1000 * i + 999));
                            } else {
                                channelAuthorizeRegionService.saveBatch(channelAuthorizeRegionTempList.subList(1000 * i, size - 1));
                            }
                        }
                    }
                    ChannelAuthorizeRegionTempsToCase.addAll(channelAuthorizeRegionTempList);
                }

                /** 保存渠道授权车型信息前先清除旧的数据*/
                channelAuthorizeVehicleTempService.remove(Wrappers.<ChannelAuthorizeVehicleTemp>query().lambda()
                        .eq(ChannelAuthorizeVehicleTemp::getChannelId, temp.getId())
                        .eq(ChannelAuthorizeVehicleTemp::getBusinessType, Constants.BUSINESS_TYPE_OLD_CAR));

                //保存渠道二手车授权车型
                List<ChannelAuthorizeVehicleTemp> channelAuthorizeVehicleList = new ArrayList<>();
                if (mainCarOld != null && mainCarOld.length > 0) {
                    for (String main : mainCarOld) {
                        ChannelAuthorizeVehicleTemp channelAuthorizeVehicleTemp = new ChannelAuthorizeVehicleTemp();
                        String code = main.split(",")[0];
                        String title = main.split(",")[1];
                        String indeterminate = main.split(",")[3];
                        String carLevel = main.split(",")[4];
                        String spellCode = main.split(",")[5];
                        String carType = main.split(",")[6];
                        String parentId = main.split(",")[2];
                        channelAuthorizeVehicleTemp.setChannelId(temp.getId());
                        channelAuthorizeVehicleTemp.setCode(code);
                        channelAuthorizeVehicleTemp.setTitle(title);
                        channelAuthorizeVehicleTemp.setParentId(parentId);
                        channelAuthorizeVehicleTemp.setCarLevel(carLevel);
                         if("null".equals(carType)){
                        channelAuthorizeVehicleTemp.setCarType("");
                    }else{
                        channelAuthorizeVehicleTemp.setCarType(carType);
                    }
                        if (StrUtil.isNotBlank(indeterminate)) {
                            channelAuthorizeVehicleTemp.setIndeterminate(indeterminate);
                        } else {
                            channelAuthorizeVehicleTemp.setIndeterminate("false");
                        }
                        if (StrUtil.isNotBlank(spellCode)) {
                            channelAuthorizeVehicleTemp.setSpellCode(spellCode);
                        }
                        channelAuthorizeVehicleTemp.setBusinessType(Constants.BUSINESS_TYPE_OLD_CAR);
                        channelAuthorizeVehicleList.add(channelAuthorizeVehicleTemp);
                    }

                    int size = channelAuthorizeVehicleList.size();
                    if (size <= 1000) {
                        channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList);
                    } else {
                        for (int i = 0; i < size / 1000; i++) {
                            if (size / 1000 - i > 1) {
                                channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList.subList(1000 * i, 1000 * i + 999));
                            } else {
                                channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList.subList(1000 * i, size - 1));
                            }
                        }
                    }
                    ChannelAuthorizeVehicleTempsToCase.addAll(channelAuthorizeVehicleList);
                }
            }

            directCarDealerConditionToCase.setChannelRiskInfoList(channelRiskInfoTempListToCase);
            directCarDealerConditionToCase.setChannelQuotaInfoTempList(channelQuotaInfoTempsToCase);
            directCarDealerConditionToCase.setChannelAuthorizeVehicleList(ChannelAuthorizeVehicleTempsToCase);
            directCarDealerConditionToCase.setChannelAuthorizeRegionList(ChannelAuthorizeRegionTempsToCase);

            //如果状态为00,启用 则同步到案件服务
            if (ENABLED.equals(temp.getChannelStatus()) || ENABLED.equals(temp.getChannelStatusOldCar())) {
                saveDirectCarDealerInfoToCase(temp.getId(), directCarDealerConditionToCase);
            }

            //审核中的状态走这里
            if (Constants.REVIEW.equals(channelCoopeCardealerTemp.getStatus())) {
                List<Object> workfolwList = new ArrayList<>();
                workfolwList.add(temp);
                workfolwList.add(channelCoopeCardealerTemp);
                directCarDealerWorkflow(workfolwList);
            }

            return IResponse.success(list);
        }

        //下面是不存在这家车商的情况
        if (StringUtils.isEmpty(temp.getChannelCode())) {
            temp.setChannelCode(directCarDealerService.channelCodeSequence("directCarDealerCode", "directCarDealerCode", Constants.DIRECTCARDEALER));
        }
        //保存直营车商的基本信息
        directCarDealerService.saveOrUpdate(temp);
        list.add(temp);
        // 保存车商信息到合作商车商关联表
        channelCoopeCardealerTemp.setCardealerId(temp.getId());
        channelCoopeCardealerService.save(channelCoopeCardealerTemp);

        list.add(channelCoopeCardealerTemp);
        directCarDealerConditionToCase.setChannelBaseInfoTemp(temp);
        directCarDealerConditionToCase.setChannelCoopeCardealerTemp(channelCoopeCardealerTemp);

        //保存主营品牌
        List<ChannelMainBrand> channelMainBrandList = new ArrayList<>();
        if (mainBrand != null && mainBrand.length > 0) {
            for (String main : mainBrand) {
                ChannelMainBrand channelMainBrand = new ChannelMainBrand();
                String code = main.split(",")[0];
                String title = main.split(",")[1];
                String indeterminate = main.split(",")[2];
                String carLevel = main.split(",")[3];
                String spellCode = main.split(",")[4];
                channelMainBrand.setChannelId(temp.getId());
                channelMainBrand.setCode(code);
                channelMainBrand.setTitle(title);
                if (StrUtil.isNotBlank(indeterminate)) {
                    channelMainBrand.setIndeterminate(indeterminate);
                } else {
                    channelMainBrand.setIndeterminate("false");
                }
                if (StrUtil.isNotBlank(spellCode)) {
                    channelMainBrand.setSpellCode(spellCode);
                }
                channelMainBrand.setCarLevel(carLevel);
                channelMainBrand.setChannelBelong(Constants.DIRECTCARDEALER);
                channelMainBrandList.add(channelMainBrand);
            }

            int size = channelMainBrandList.size();
            if (size <= 1000) {
                channelMainBrandService.saveBatch(channelMainBrandList);
            } else {
                for (int i = 0; i < size / 1000; i++) {
                    if (size / 1000 - i > 1) {
                        channelMainBrandService.saveBatch(channelMainBrandList.subList(1000 * i, 1000 * i + 999));
                    } else {
                        channelMainBrandService.saveBatch(channelMainBrandList.subList(1000 * i, size - 1));
                    }
                }
            }
            directCarDealerConditionToCase.setMainBrandList(channelMainBrandList);

        }

        /** 更新车商风控信息*/
        //判断当前登陆者是否拥有新车权限，由前端传入
        if (ChannelOnlineConstants.IS_HAVE_CAR_ROLE_YES.equals(condition.getIsNewCarRole())) {
            /** 保存渠道新车风控信息*/
            //渠道id赋值
            channelRiskInfoTemp.setChannelId(temp.getId());
            //清楚旧数据
            channelRiskInfoService.remove(Wrappers.<ChannelRiskInfoTemp>query().lambda()
                    .eq(ChannelRiskInfoTemp::getChannelId, temp.getId())
                    .eq(ChannelRiskInfoTemp::getBusinessType, Constants.BUSINESS_TYPE_NEW_CAR));
            channelRiskInfoService.saveOrUpdate(channelRiskInfoTemp);
            channelRiskInfoTempListToCase.add(channelRiskInfoTemp);


            /** 保存新车保证金信息前先清除旧的数据*/
            channelQuotaInfoService.remove(Wrappers.<ChannelQuotaInfoTemp>query().lambda()
                    .eq(ChannelQuotaInfoTemp::getChannelId, temp.getId())
                    .eq(ChannelQuotaInfoTemp::getBusinessType, Constants.BUSINESS_TYPE_NEW_CAR));
            //保存新车保证金信息
            for (ChannelQuotaInfoTemp quotaInfo : channelQuotaInfoList) {
                quotaInfo.setChannelId(temp.getId());
                //临时额度
                BigDecimal tempQuota = quotaInfo.getTempQuota() == null ? BigDecimal.ZERO : quotaInfo.getTempQuota();
                //签放额度
                BigDecimal quotaSigning = quotaInfo.getQuotaAmount() == null ? BigDecimal.ZERO : quotaInfo.getQuotaAmount();
                //剩余额度 = 临时额度+签放额度
                quotaInfo.setSurplusQuota(tempQuota.add(quotaSigning));
                //占用额度为0
                quotaInfo.setOccupiedQuota(BigDecimal.ZERO);
                channelQuotaInfoService.saveOrUpdate(quotaInfo);
                channelQuotaInfoTempsToCase.add(quotaInfo);
            }


            /** 保存渠道新车授权区域信息前先清除旧的数据*/
            channelAuthorizeRegionService.remove(Wrappers.<ChannelAuthorizeRegionTemp>query().lambda()
                    .eq(ChannelAuthorizeRegionTemp::getChannelId, temp.getId())
                    .eq(ChannelAuthorizeRegionTemp::getBusinessType, Constants.BUSINESS_TYPE_NEW_CAR));
            //保存渠道新车授权区域
            List<ChannelAuthorizeRegionTemp> channelAuthorizeRegionTempList = new ArrayList<>();
            if (mainArea != null && mainArea.length > 0) {
                for (String area : mainArea) {
                    ChannelAuthorizeRegionTemp regionTemp = new ChannelAuthorizeRegionTemp();
                    String code = area.split(",")[0];
                    String title = area.split(",")[1];
                    String isParent = area.split(",")[2];
                    String parentId = area.split(",")[3];
                    regionTemp.setChannelId(temp.getId());
                    regionTemp.setCode(code);
                    regionTemp.setTitle(title);
                    regionTemp.setIsParent(isParent);
                    regionTemp.setParentId(parentId);
                    regionTemp.setBusinessType(Constants.BUSINESS_TYPE_NEW_CAR);
                    channelAuthorizeRegionTempList.add(regionTemp);
                }
                int size = channelAuthorizeRegionTempList.size();
                if (size <= 1000) {
                    channelAuthorizeRegionService.saveOrUpdateBatch(channelAuthorizeRegionTempList);
                } else {
                    for (int i = 0; i < size / 1000; i++) {
                        if (size / 1000 - i > 1) {
                            channelAuthorizeRegionService.saveOrUpdateBatch(channelAuthorizeRegionTempList.subList(1000 * i, 1000 * i + 999));
                        } else {
                            channelAuthorizeRegionService.saveOrUpdateBatch(channelAuthorizeRegionTempList.subList(1000 * i, size - 1));
                        }
                    }
                }

                ChannelAuthorizeRegionTempsToCase.addAll(channelAuthorizeRegionTempList);
            }


            /** 保存渠道授权车型信息前先清除旧的数据*/
            channelAuthorizeVehicleTempService.remove(Wrappers.<ChannelAuthorizeVehicleTemp>query().lambda()
                    .eq(ChannelAuthorizeVehicleTemp::getChannelId, temp.getId())
                    .eq(ChannelAuthorizeVehicleTemp::getBusinessType, Constants.BUSINESS_TYPE_NEW_CAR));
            //保存渠道新车授权车型
            List<ChannelAuthorizeVehicleTemp> channelAuthorizeVehicleList = new ArrayList<>();
            if (mainCar != null && mainCar.length > 0) {
                for (String main : mainCar) {
                    ChannelAuthorizeVehicleTemp channelAuthorizeVehicleTemp = new ChannelAuthorizeVehicleTemp();
                    String code = main.split(",")[0];
                    String title = main.split(",")[1];
                    String indeterminate = main.split(",")[3];
                    String carLevel = main.split(",")[4];
                    String spellCode = main.split(",")[5];
                    String carType = main.split(",")[6];
                    String parentId = main.split(",")[2];
                    channelAuthorizeVehicleTemp.setChannelId(temp.getId());
                    channelAuthorizeVehicleTemp.setCode(code);
                    channelAuthorizeVehicleTemp.setTitle(title);
                    channelAuthorizeVehicleTemp.setParentId(parentId);
                    channelAuthorizeVehicleTemp.setCarLevel(carLevel);
                     if("null".equals(carType)){
                        channelAuthorizeVehicleTemp.setCarType("");
                    }else{
                        channelAuthorizeVehicleTemp.setCarType(carType);
                    }
                    if (StrUtil.isNotBlank(indeterminate)) {
                        channelAuthorizeVehicleTemp.setIndeterminate(indeterminate);
                    } else {
                        channelAuthorizeVehicleTemp.setIndeterminate("false");
                    }
                    if (StrUtil.isNotBlank(spellCode)) {
                        channelAuthorizeVehicleTemp.setSpellCode(spellCode);
                    }
                    channelAuthorizeVehicleTemp.setBusinessType(Constants.BUSINESS_TYPE_NEW_CAR);
                    channelAuthorizeVehicleList.add(channelAuthorizeVehicleTemp);
                }

                int size = channelAuthorizeVehicleList.size();
                if (size <= 1000) {
                    channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList);
                } else {
                    for (int i = 0; i < size / 1000; i++) {
                        if (size / 1000 - i > 1) {
                            channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList.subList(1000 * i, 1000 * i + 999));
                        } else {
                            channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList.subList(1000 * i, size - 1));
                        }
                    }
                }
                ChannelAuthorizeVehicleTempsToCase.addAll(channelAuthorizeVehicleList);
            }
        }


        //判断当前登陆者是否拥有二手车权限，由前端传入
        if (ChannelOnlineConstants.IS_HAVE_CAR_ROLE_YES.equals(condition.getIsOldCarRole())) {
            //渠道id赋值
            channelRiskInfoTempOld.setChannelId(temp.getId());
            //二手车风控信息查询判断
            channelRiskInfoService.remove(Wrappers.<ChannelRiskInfoTemp>query().lambda()
                    .eq(ChannelRiskInfoTemp::getChannelId, temp.getId())
                    .eq(ChannelRiskInfoTemp::getBusinessType, Constants.BUSINESS_TYPE_OLD_CAR));
            channelRiskInfoService.saveOrUpdate(channelRiskInfoTempOld);
            channelRiskInfoTempListToCase.add(channelRiskInfoTempOld);

            list.add(channelRiskInfoTemp);

            /** 保存渠道二手车保证金信息前先清除旧的数据*/
            channelQuotaInfoService.remove(Wrappers.<ChannelQuotaInfoTemp>query().lambda()
                    .eq(ChannelQuotaInfoTemp::getChannelId, temp.getId())
                    .eq(ChannelQuotaInfoTemp::getBusinessType, Constants.BUSINESS_TYPE_OLD_CAR));
            //保存二手车保证金信息
            for (ChannelQuotaInfoTemp quotaInfo : channelQuotaInfoListOld) {
                quotaInfo.setChannelId(temp.getId());
                //临时额度
                BigDecimal tempQuota = quotaInfo.getTempQuota() == null ? BigDecimal.ZERO : quotaInfo.getTempQuota();
                //签放额度
                BigDecimal quotaSigning = quotaInfo.getQuotaAmount() == null ? BigDecimal.ZERO : quotaInfo.getQuotaAmount();
                //剩余额度 = 临时额度+签放额度
                quotaInfo.setSurplusQuota(tempQuota.add(quotaSigning));
                //占用额度为0
                quotaInfo.setOccupiedQuota(BigDecimal.ZERO);

                channelQuotaInfoService.saveOrUpdate(quotaInfo);
                channelQuotaInfoTempsToCase.add(quotaInfo);
            }

            /** 保存渠道二手车授权区域信息前先清除旧的数据*/
            channelAuthorizeRegionService.remove(Wrappers.<ChannelAuthorizeRegionTemp>query().lambda()
                    .eq(ChannelAuthorizeRegionTemp::getChannelId, temp.getId())
                    .eq(ChannelAuthorizeRegionTemp::getBusinessType, Constants.BUSINESS_TYPE_OLD_CAR));
            //保存渠道二手车授权区域
            List<ChannelAuthorizeRegionTemp> channelAuthorizeRegionTempList = new ArrayList<>();
            if (mainAreaOld != null && mainAreaOld.length > 0) {
                for (String area : mainAreaOld) {
                    ChannelAuthorizeRegionTemp regionTemp = new ChannelAuthorizeRegionTemp();
                    String code = area.split(",")[0];
                    String title = area.split(",")[1];
                    String isParent = area.split(",")[2];
                    String parentId = area.split(",")[3];
                    regionTemp.setChannelId(temp.getId());
                    regionTemp.setCode(code);
                    regionTemp.setTitle(title);
                    regionTemp.setIsParent(isParent);
                    regionTemp.setParentId(parentId);
                    regionTemp.setBusinessType(Constants.BUSINESS_TYPE_OLD_CAR);
                    channelAuthorizeRegionTempList.add(regionTemp);
                }
                int size = channelAuthorizeRegionTempList.size();
                if (size <= 1000) {
                    channelAuthorizeRegionService.saveBatch(channelAuthorizeRegionTempList);
                } else {
                    for (int i = 0; i < size / 1000; i++) {
                        if (size / 1000 - i > 1) {
                            channelAuthorizeRegionService.saveBatch(channelAuthorizeRegionTempList.subList(1000 * i, 1000 * i + 999));
                        } else {
                            channelAuthorizeRegionService.saveBatch(channelAuthorizeRegionTempList.subList(1000 * i, size - 1));
                        }
                    }
                }
                ChannelAuthorizeRegionTempsToCase.addAll(channelAuthorizeRegionTempList);
            }

            /** 保存渠道授权车型信息前先清除旧的数据*/
            channelAuthorizeVehicleTempService.remove(Wrappers.<ChannelAuthorizeVehicleTemp>query().lambda()
                    .eq(ChannelAuthorizeVehicleTemp::getChannelId, temp.getId())
                    .eq(ChannelAuthorizeVehicleTemp::getBusinessType, Constants.BUSINESS_TYPE_OLD_CAR));

            //保存渠道二手车授权车型
            List<ChannelAuthorizeVehicleTemp> channelAuthorizeVehicleList = new ArrayList<>();
            if (mainCarOld != null && mainCarOld.length > 0) {
                for (String main : mainCarOld) {
                    ChannelAuthorizeVehicleTemp channelAuthorizeVehicleTemp = new ChannelAuthorizeVehicleTemp();
                    String code = main.split(",")[0];
                    String title = main.split(",")[1];
                    String indeterminate = main.split(",")[3];
                    String carLevel = main.split(",")[4];
                    String spellCode = main.split(",")[5];
                    String carType = main.split(",")[6];
                    String parentId = main.split(",")[2];
                    channelAuthorizeVehicleTemp.setChannelId(temp.getId());
                    channelAuthorizeVehicleTemp.setCode(code);
                    channelAuthorizeVehicleTemp.setTitle(title);
                    channelAuthorizeVehicleTemp.setParentId(parentId);
                    channelAuthorizeVehicleTemp.setCarLevel(carLevel);
                     if("null".equals(carType)){
                        channelAuthorizeVehicleTemp.setCarType("");
                    }else{
                        channelAuthorizeVehicleTemp.setCarType(carType);
                    }
                    if (StrUtil.isNotBlank(indeterminate)) {
                        channelAuthorizeVehicleTemp.setIndeterminate(indeterminate);
                    } else {
                        channelAuthorizeVehicleTemp.setIndeterminate("false");
                    }
                    if (StrUtil.isNotBlank(spellCode)) {
                        channelAuthorizeVehicleTemp.setSpellCode(spellCode);
                    }
                    channelAuthorizeVehicleTemp.setBusinessType(Constants.BUSINESS_TYPE_OLD_CAR);
                    channelAuthorizeVehicleList.add(channelAuthorizeVehicleTemp);
                }
                int size = channelAuthorizeVehicleList.size();
                if (size <= 1000) {
                    channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList);
                } else {
                    for (int i = 0; i < size / 1000; i++) {
                        if (size / 1000 - i > 1) {
                            channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList.subList(1000 * i, 1000 * i + 999));
                        } else {
                            channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList.subList(1000 * i, size - 1));
                        }
                    }
                }
                ChannelAuthorizeVehicleTempsToCase.addAll(channelAuthorizeVehicleList);
            }
        }

        directCarDealerConditionToCase.setChannelRiskInfoList(channelRiskInfoTempListToCase);
        directCarDealerConditionToCase.setChannelQuotaInfoTempList(channelQuotaInfoTempsToCase);
        directCarDealerConditionToCase.setChannelAuthorizeVehicleList(ChannelAuthorizeVehicleTempsToCase);
        directCarDealerConditionToCase.setChannelAuthorizeRegionList(ChannelAuthorizeRegionTempsToCase);

        //如果状态为00,启用 则同步到案件服务
        if (ENABLED.equals(temp.getChannelStatus()) || ENABLED.equals(temp.getChannelStatusOldCar())) {
            saveDirectCarDealerInfoToCase(temp.getId(), directCarDealerConditionToCase);
        }

        //审核中的状态走这里
        if (Constants.REVIEW.equals(channelCoopeCardealerTemp.getStatus())) {
            List<Object> workfolwList = new ArrayList<>();
            workfolwList.add(temp);
            workfolwList.add(channelCoopeCardealerTemp);
            directCarDealerWorkflow(workfolwList);
        }

        return IResponse.success(list);
    }

    @RequestMapping(value = "/stagingSaveDirectCarDealer", method = RequestMethod.POST)
    @ApiOperation(value = "暂存直营车商申请信息")
    @SysLog("暂存直营车商申请信息")
    @Transactional(rollbackFor = Exception.class)
    public IResponse stagingSaveDirectCarDealer(@RequestBody DirectCarDealerCondition condition) {

        List list = new ArrayList<>();
        //从前端传来的数据中拿到直营车商的基本信息
        DirectCarDealer temp = condition.getChannelBaseInfoTemp();
        //从前端传来的数据中拿到中间表信息
        ChannelCoopeCardealerTemp channelCoopeCardealerTemp = condition.getChannelCoopeCardealerTemp();
        //风控信息
        ChannelRiskInfoTemp channelRiskInfoTemp = condition.getChannelRiskInfoTemp();
        //保证金信息
        List<ChannelQuotaInfoTemp> channelQuotaInfoList = condition.getChannelQuotaInfoTempList();
        /** 保存渠道二手车风控信息*/
        ChannelRiskInfoTemp channelRiskInfoTempOld = condition.getChannelRiskInfoTempOld();
        //二手车保证金
        List<ChannelQuotaInfoTemp> channelQuotaInfoListOld = condition.getChannelQuotaInfoTempOldList();
        //主营品牌
        String[] mainBrand = condition.getMainBrand();

        //新车授权区域
        String[] mainArea = condition.getMainArea();
        //二手车授权区域
        String[] mainAreaOld = condition.getMainAreaOld();
        //授权车型
        String[] mainCar = condition.getMainCar();
        //二手车授权车型
        String[] mainCarOld = condition.getMainCarOld();

        //省市地址
        String[] channelAdminAddressValue = condition.getChannelAdminAddressValue();
        String[] channelAddressValue = condition.getChannelAddressValue();

        if (channelAdminAddressValue != null && channelAdminAddressValue.length > 0) {
            temp.setChannelAdminProvince(channelAdminAddressValue[0]);
            temp.setChannelAdminCity(channelAdminAddressValue[1]);
        }
        if (channelAddressValue != null && channelAddressValue.length > 0) {
            temp.setChannelProvince(channelAddressValue[0]);
            temp.setChannelCity(channelAddressValue[1]);
        }

        /*//根据统一社会信用码判断是否已存在这家车商
        List<DirectCarDealer> resultList = directCarDealerService.list(Wrappers.<DirectCarDealer>query().lambda().eq(DirectCarDealer::getSocUniCrtCode, temp.getSocUniCrtCode()));
        if (resultList != null && resultList.size() > 0) {
            //已存在这家车商情况,判断是否停用
            Long carDealerId = null;
            for (DirectCarDealer temp1 : resultList) {
                if (Constants.DISABLE.equals(temp1.getChannelStatus())) {
                    return IResponse.fail("该车商已停用");
                }
                return IResponse.fail("系统已存在该车商信息");
            }
        }*/

        //下面是不存在这家车商的情况
        if (StringUtils.isEmpty(temp.getChannelCode())) {
            temp.setChannelCode(directCarDealerService.channelCodeSequence("directCarDealerCode", "directCarDealerCode", Constants.DIRECTCARDEALER));
        }
        //保存直营车商的基本信息
        directCarDealerService.saveOrUpdate(temp);
        list.add(temp);
        // 保存车商信息到合作商车商关联表
        channelCoopeCardealerTemp.setCardealerId(temp.getId());
        channelCoopeCardealerService.remove(Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                .eq(ChannelCoopeCardealerTemp::getCardealerId, temp.getId())
        );
        channelCoopeCardealerService.save(channelCoopeCardealerTemp);
        list.add(channelCoopeCardealerTemp);

        //保存主营品牌
        List<ChannelMainBrand> channelMainBrandList = new ArrayList<>();
        if (mainBrand != null && mainBrand.length > 0) {
            for (String main : mainBrand) {
                ChannelMainBrand channelMainBrand = new ChannelMainBrand();
                String code = main.split(",")[0];
                String title = main.split(",")[1];
                String indeterminate = main.split(",")[2];
                String carLevel = main.split(",")[3];
                String spellCode = main.split(",")[4];
                channelMainBrand.setChannelId(temp.getId());
                channelMainBrand.setCode(code);
                channelMainBrand.setTitle(title);
                if (StrUtil.isNotBlank(indeterminate)) {
                    channelMainBrand.setIndeterminate(indeterminate);
                } else {
                    channelMainBrand.setIndeterminate("false");
                }
                if (StrUtil.isNotBlank(spellCode)) {
                    channelMainBrand.setSpellCode(spellCode);
                }
                channelMainBrand.setCarLevel(carLevel);
                channelMainBrand.setChannelBelong(Constants.DIRECTCARDEALER);
                channelMainBrandList.add(channelMainBrand);
            }
            //  channelMainBrandService.saveOrUpdateBatch(channelMainBrandList);

            int size = channelMainBrandList.size();
            if (size <= 1000) {
                channelMainBrandService.saveBatch(channelMainBrandList);
            } else {
                for (int i = 0; i < size / 1000; i++) {
                    if (size / 1000 - i > 1) {
                        channelMainBrandService.saveBatch(channelMainBrandList.subList(1000 * i, 1000 * i + 999));
                    } else {
                        channelMainBrandService.saveBatch(channelMainBrandList.subList(1000 * i, size - 1));
                    }
                }
            }
        }

        /** 保存车商风控信息*/
        //判断当前登陆者是否拥有新车权限，由前端传入
        if (ChannelOnlineConstants.IS_HAVE_CAR_ROLE_YES.equals(condition.getIsNewCarRole())) {
            /** 保存渠道新车风控信息*/
            //渠道id赋值
            channelRiskInfoTemp.setChannelId(temp.getId());
            //清楚旧数据
            channelRiskInfoService.remove(Wrappers.<ChannelRiskInfoTemp>query().lambda()
                    .eq(ChannelRiskInfoTemp::getChannelId, temp.getId())
                    .eq(ChannelRiskInfoTemp::getBusinessType, Constants.BUSINESS_TYPE_NEW_CAR));
            channelRiskInfoService.saveOrUpdate(channelRiskInfoTemp);

            /** 保存新车保证金信息前先清除旧的数据*/
            channelQuotaInfoService.remove(Wrappers.<ChannelQuotaInfoTemp>query().lambda()
                    .eq(ChannelQuotaInfoTemp::getChannelId, temp.getId())
                    .eq(ChannelQuotaInfoTemp::getBusinessType, Constants.BUSINESS_TYPE_NEW_CAR));
            //保存新车保证金信息
            for (ChannelQuotaInfoTemp quotaInfo : channelQuotaInfoList) {
                quotaInfo.setChannelId(temp.getId());
                //临时额度
                BigDecimal tempQuota = quotaInfo.getTempQuota() == null ? BigDecimal.ZERO : quotaInfo.getTempQuota();
                //签放额度
                BigDecimal quotaSigning = quotaInfo.getQuotaAmount() == null ? BigDecimal.ZERO : quotaInfo.getQuotaAmount();
                //剩余额度 = 临时额度+签放额度
                quotaInfo.setSurplusQuota(tempQuota.add(quotaSigning));
                //占用额度为0
                quotaInfo.setOccupiedQuota(BigDecimal.ZERO);
                channelQuotaInfoService.saveOrUpdate(quotaInfo);
            }

            /** 保存渠道新车授权区域信息前先清除旧的数据*/
            channelAuthorizeRegionService.remove(Wrappers.<ChannelAuthorizeRegionTemp>query().lambda()
                    .eq(ChannelAuthorizeRegionTemp::getChannelId, temp.getId())
                    .eq(ChannelAuthorizeRegionTemp::getBusinessType, Constants.BUSINESS_TYPE_NEW_CAR));
            //保存渠道新车授权区域
            List<ChannelAuthorizeRegionTemp> channelAuthorizeRegionTempList = new ArrayList<>();
            if (mainArea != null && mainArea.length > 0) {
                for (String area : mainArea) {
                    ChannelAuthorizeRegionTemp regionTemp = new ChannelAuthorizeRegionTemp();
                    String code = area.split(",")[0];
                    String title = area.split(",")[1];
                    String isParent = area.split(",")[2];
                    String parentId = area.split(",")[3];
                    regionTemp.setChannelId(temp.getId());
                    regionTemp.setCode(code);
                    regionTemp.setTitle(title);
                    regionTemp.setIsParent(isParent);
                    regionTemp.setParentId(parentId);
                    regionTemp.setBusinessType(Constants.BUSINESS_TYPE_NEW_CAR);
                    channelAuthorizeRegionTempList.add(regionTemp);
                }
                int size = channelAuthorizeRegionTempList.size();
                if (size <= 1000) {
                    channelAuthorizeRegionService.saveOrUpdateBatch(channelAuthorizeRegionTempList);
                } else {
                    for (int i = 0; i < size / 1000; i++) {
                        if (size / 1000 - i > 1) {
                            channelAuthorizeRegionService.saveOrUpdateBatch(channelAuthorizeRegionTempList.subList(1000 * i, 1000 * i + 999));
                        } else {
                            channelAuthorizeRegionService.saveOrUpdateBatch(channelAuthorizeRegionTempList.subList(1000 * i, size - 1));
                        }
                    }
                }
                /*for(ChannelAuthorizeRegionTemp regionTemp : channelAuthorizeRegionTempList){
                    channelAuthorizeRegionService.saveOrUpdateBatch(regionTemp);
                }*/
            }

            /** 保存渠道授权车型信息前先清除旧的数据*/
            channelAuthorizeVehicleTempService.remove(Wrappers.<ChannelAuthorizeVehicleTemp>query().lambda()
                    .eq(ChannelAuthorizeVehicleTemp::getChannelId, temp.getId())
                    .eq(ChannelAuthorizeVehicleTemp::getBusinessType, Constants.BUSINESS_TYPE_NEW_CAR));
            //保存渠道新车授权车型
            List<ChannelAuthorizeVehicleTemp> channelAuthorizeVehicleList = new ArrayList<>();
            if (mainCar != null && mainCar.length > 0) {
                for (String main : mainCar) {
                    ChannelAuthorizeVehicleTemp channelAuthorizeVehicleTemp = new ChannelAuthorizeVehicleTemp();
                    String code = main.split(",")[0];
                    String title = main.split(",")[1];
                    String indeterminate = main.split(",")[3];
                    String carLevel = main.split(",")[4];
                    String spellCode = main.split(",")[5];
                    String carType = main.split(",")[6];
                    String parentId = main.split(",")[2];
                    channelAuthorizeVehicleTemp.setChannelId(temp.getId());
                    channelAuthorizeVehicleTemp.setCode(code);
                    channelAuthorizeVehicleTemp.setTitle(title);
                    channelAuthorizeVehicleTemp.setParentId(parentId);
                    channelAuthorizeVehicleTemp.setCarLevel(carLevel);
                     if("null".equals(carType)){
                        channelAuthorizeVehicleTemp.setCarType("");
                    }else{
                        channelAuthorizeVehicleTemp.setCarType(carType);
                    }
                    if (StrUtil.isNotBlank(indeterminate)) {
                        channelAuthorizeVehicleTemp.setIndeterminate(indeterminate);
                    } else {
                        channelAuthorizeVehicleTemp.setIndeterminate("false");
                    }
                    if (StrUtil.isNotBlank(spellCode)) {
                        channelAuthorizeVehicleTemp.setSpellCode(spellCode);
                    }
                    channelAuthorizeVehicleTemp.setBusinessType(Constants.BUSINESS_TYPE_NEW_CAR);
                    channelAuthorizeVehicleList.add(channelAuthorizeVehicleTemp);
                }
               /* for(ChannelAuthorizeVehicleTemp vehicleTemp : channelAuthorizeVehicleList){
                    channelAuthorizeVehicleTempService.saveOrUpdate(vehicleTemp);
                }*/
                int size = channelAuthorizeVehicleList.size();
                if (size <= 1000) {
                    channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList);
                } else {
                    for (int i = 0; i < size / 1000; i++) {
                        if (size / 1000 - i > 1) {
                            channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList.subList(1000 * i, 1000 * i + 999));
                        } else {
                            channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList.subList(1000 * i, size - 1));
                        }
                    }
                }
                // channelAuthorizeVehicleTempService.saveOrUpdateBatch(channelAuthorizeVehicleList);
            }
        }


        //判断当前登陆者是否拥有二手车权限，由前端传入
        if (ChannelOnlineConstants.IS_HAVE_CAR_ROLE_YES.equals(condition.getIsOldCarRole())) {
            //渠道id赋值
            channelRiskInfoTempOld.setChannelId(temp.getId());
            //二手车风控信息查询判断
            channelRiskInfoService.remove(Wrappers.<ChannelRiskInfoTemp>query().lambda()
                    .eq(ChannelRiskInfoTemp::getChannelId, temp.getId())
                    .eq(ChannelRiskInfoTemp::getBusinessType, Constants.BUSINESS_TYPE_OLD_CAR));
            channelRiskInfoService.saveOrUpdate(channelRiskInfoTempOld);
            // directCarDealerConditionToCase.setChannelRiskInfoList(channelRiskInfoTempListToCase);

            list.add(channelRiskInfoTemp);

            /** 保存渠道二手车保证金信息前先清除旧的数据*/
            channelQuotaInfoService.remove(Wrappers.<ChannelQuotaInfoTemp>query().lambda()
                    .eq(ChannelQuotaInfoTemp::getChannelId, temp.getId())
                    .eq(ChannelQuotaInfoTemp::getBusinessType, Constants.BUSINESS_TYPE_OLD_CAR));
            //保存二手车保证金信息
            for (ChannelQuotaInfoTemp quotaInfo : channelQuotaInfoListOld) {
                quotaInfo.setChannelId(temp.getId());
                //临时额度
                BigDecimal tempQuota = quotaInfo.getTempQuota() == null ? BigDecimal.ZERO : quotaInfo.getTempQuota();
                //签放额度
                BigDecimal quotaSigning = quotaInfo.getQuotaAmount() == null ? BigDecimal.ZERO : quotaInfo.getQuotaAmount();
                //剩余额度 = 临时额度+签放额度
                quotaInfo.setSurplusQuota(tempQuota.add(quotaSigning));
                //占用额度为0
                quotaInfo.setOccupiedQuota(BigDecimal.ZERO);

                channelQuotaInfoService.saveOrUpdate(quotaInfo);
            }

            /** 保存渠道二手车授权区域信息前先清除旧的数据*/
            channelAuthorizeRegionService.remove(Wrappers.<ChannelAuthorizeRegionTemp>query().lambda()
                    .eq(ChannelAuthorizeRegionTemp::getChannelId, temp.getId())
                    .eq(ChannelAuthorizeRegionTemp::getBusinessType, Constants.BUSINESS_TYPE_OLD_CAR));
            //保存渠道二手车授权区域
            List<ChannelAuthorizeRegionTemp> channelAuthorizeRegionTempList = new ArrayList<>();
            if (mainAreaOld != null && mainAreaOld.length > 0) {
                for (String area : mainAreaOld) {
                    ChannelAuthorizeRegionTemp regionTemp = new ChannelAuthorizeRegionTemp();
                    String code = area.split(",")[0];
                    String title = area.split(",")[1];
                    String isParent = area.split(",")[2];
                    String parentId = area.split(",")[3];
                    regionTemp.setChannelId(temp.getId());
                    regionTemp.setCode(code);
                    regionTemp.setTitle(title);
                    regionTemp.setIsParent(isParent);
                    regionTemp.setParentId(parentId);
                    regionTemp.setBusinessType(Constants.BUSINESS_TYPE_OLD_CAR);
                    channelAuthorizeRegionTempList.add(regionTemp);
                }
                /*for(ChannelAuthorizeRegionTemp regionTemp : channelAuthorizeRegionTempList){
                    channelAuthorizeRegionService.saveOrUpdate(regionTemp);
                }*/
                int size = channelAuthorizeRegionTempList.size();
                if (size <= 1000) {
                    channelAuthorizeRegionService.saveBatch(channelAuthorizeRegionTempList);
                } else {
                    for (int i = 0; i < size / 1000; i++) {
                        if (size / 1000 - i > 1) {
                            channelAuthorizeRegionService.saveBatch(channelAuthorizeRegionTempList.subList(1000 * i, 1000 * i + 999));
                        } else {
                            channelAuthorizeRegionService.saveBatch(channelAuthorizeRegionTempList.subList(1000 * i, size - 1));
                        }
                    }
                }
                // channelAuthorizeRegionService.saveOrUpdateBatch(channelAuthorizeRegionTempList);
            }

            /** 保存渠道授权车型信息前先清除旧的数据*/
            channelAuthorizeVehicleTempService.remove(Wrappers.<ChannelAuthorizeVehicleTemp>query().lambda()
                    .eq(ChannelAuthorizeVehicleTemp::getChannelId, temp.getId())
                    .eq(ChannelAuthorizeVehicleTemp::getBusinessType, Constants.BUSINESS_TYPE_OLD_CAR));

            //保存渠道二手车授权车型
            List<ChannelAuthorizeVehicleTemp> channelAuthorizeVehicleList = new ArrayList<>();
            if (mainCarOld != null && mainCarOld.length > 0) {
                for (String main : mainCarOld) {
                    ChannelAuthorizeVehicleTemp channelAuthorizeVehicleTemp = new ChannelAuthorizeVehicleTemp();
                    String code = main.split(",")[0];
                    String title = main.split(",")[1];
                    String indeterminate = main.split(",")[3];
                    String carLevel = main.split(",")[4];
                    String spellCode = main.split(",")[5];
                    String carType = main.split(",")[6];
                    String parentId = main.split(",")[2];
                    channelAuthorizeVehicleTemp.setChannelId(temp.getId());
                    channelAuthorizeVehicleTemp.setCode(code);
                    channelAuthorizeVehicleTemp.setTitle(title);
                    channelAuthorizeVehicleTemp.setParentId(parentId);
                    channelAuthorizeVehicleTemp.setCarLevel(carLevel);
                     if("null".equals(carType)){
                        channelAuthorizeVehicleTemp.setCarType("");
                    }else{
                        channelAuthorizeVehicleTemp.setCarType(carType);
                    }
                    if (StrUtil.isNotBlank(indeterminate)) {
                        channelAuthorizeVehicleTemp.setIndeterminate(indeterminate);
                    } else {
                        channelAuthorizeVehicleTemp.setIndeterminate("false");
                    }
                    if (StrUtil.isNotBlank(spellCode)) {
                        channelAuthorizeVehicleTemp.setSpellCode(spellCode);
                    }
                    channelAuthorizeVehicleTemp.setBusinessType(Constants.BUSINESS_TYPE_OLD_CAR);
                    channelAuthorizeVehicleList.add(channelAuthorizeVehicleTemp);
                }
                /*for(ChannelAuthorizeVehicleTemp vehicleTemp : channelAuthorizeVehicleList){
                    channelAuthorizeVehicleTempService.saveOrUpdate(vehicleTemp);
                }*/
                int size = channelAuthorizeVehicleList.size();
                if (size <= 1000) {
                    channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList);
                } else {
                    for (int i = 0; i < size / 1000; i++) {
                        if (size / 1000 - i > 1) {
                            channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList.subList(1000 * i, 1000 * i + 999));
                        } else {
                            channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList.subList(1000 * i, size - 1));
                        }
                    }
                }
                // channelAuthorizeVehicleTempService.saveOrUpdateBatch(channelAuthorizeVehicleList);
            }
        }

        return IResponse.success(list);
    }


    @RequestMapping(value = "/updateDirectCarDealer", method = RequestMethod.POST)
    @ApiOperation(value = "更新直营车商信息")
    @SysLog("更新直营车商信息")
    @Transactional(rollbackFor = Exception.class)
    public IResponse updateDirectCarDealer(@RequestBody DirectCarDealerCondition condition) throws JsonProcessingException {

        List list = new ArrayList<>();

        //推送到案件的数据
        DirectCarDealerCondition directCarDealerConditionToCase = new DirectCarDealerCondition();

        List<ChannelRiskInfoTemp> channelRiskInfoTempListToCase = new ArrayList<>();
        ArrayList<ChannelQuotaInfoTemp> channelQuotaInfoTempsToCase = new ArrayList<>();
        ArrayList<ChannelAuthorizeVehicleTemp> ChannelAuthorizeVehicleTempsToCase = new ArrayList<>();
        ArrayList<ChannelAuthorizeRegionTemp> ChannelAuthorizeRegionTempsToCase = new ArrayList<>();


        //从前端传来的数据中拿到直营车商的基本信息
        DirectCarDealer temp = condition.getChannelBaseInfoTemp();
        //从前端传来的数据中拿到关联表基本信息
        ChannelCoopeCardealerTemp channelCoopeCardealerTemp = condition.getChannelCoopeCardealerTemp();
        //新车风控信息
        ChannelRiskInfoTemp channelRiskInfoTemp = condition.getChannelRiskInfoTemp();
        //新车保证金信息
        List<ChannelQuotaInfoTemp> channelQuotaInfoList = condition.getChannelQuotaInfoTempList();
        /**二手车风控信息*/
        ChannelRiskInfoTemp channelRiskInfoTempOld = condition.getChannelRiskInfoTempOld();
        //二手车保证金
        List<ChannelQuotaInfoTemp> channelQuotaInfoListOld = condition.getChannelQuotaInfoTempOldList();
        //主营品牌
        String[] mainBrand = condition.getMainBrand();

        //新车授权区域
        String[] mainArea = condition.getMainArea();
        //二手车授权区域
        String[] mainAreaOld = condition.getMainAreaOld();
        //新车授权车型
        String[] mainCar = condition.getMainCar();
        //二手车授权车型
        String[] mainCarOld = condition.getMainCarOld();

        //省市地址
        String[] channelAddressValue = condition.getChannelAddressValue();


        if (channelAddressValue != null && channelAddressValue.length > 0) {
            temp.setChannelProvince(channelAddressValue[0]);
            temp.setChannelCity(channelAddressValue[1]);
        }

        //根据统一社会信用码判断是否已存在已启用这家车商
        List<DirectCarDealer> enableDealerList = directCarDealerService.list(Wrappers.<DirectCarDealer>query().lambda()
                .eq(DirectCarDealer::getSocUniCrtCode, temp.getSocUniCrtCode())
                .eq(DirectCarDealer::getChannelType, temp.getChannelType())
                .ne(DirectCarDealer::getId, temp.getId())
                .and(wrapper1 -> wrapper1.eq(DirectCarDealer::getChannelStatusOldCar, ENABLED)
                        .or(wrapper2 -> wrapper2.eq(DirectCarDealer::getChannelStatus, ENABLED))
                )
        );


        List<DirectCarDealer> allDealerList = directCarDealerService.list(Wrappers.<DirectCarDealer>query().lambda()
                .eq(DirectCarDealer::getSocUniCrtCode, temp.getSocUniCrtCode())
                .eq(DirectCarDealer::getChannelType, temp.getChannelType())
        );

        //判断更新的车商是否是草稿,如果状态是启用就更新车商,否则就新增一条记录
        Long carDealerId = null;
        if (enableDealerList.size() > 0) {
            carDealerId = enableDealerList.get(0).getId();

            if (ENABLED.equals(temp.getChannelStatus()) || ENABLED.equals(temp.getChannelStatusOldCar())) {

                //更新附件
                List<ComAttachmentFile> fileList = comAttachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda()
                        .eq(ComAttachmentFile::getBelongNo, channelCoopeCardealerTemp.getChannelId().toString())
                        .eq(ComAttachmentFile::getBusiNo, temp.getId()));
                if (CollectionUtil.isNotEmpty(fileList)) {
                    for (ComAttachmentFile file : fileList) {
                        file.setBusiNo(carDealerId.toString());
                    }
                    comAttachmentFileService.updateBatchById(fileList);
                }

                //合并前要把旧的风控信息等删掉
                directCarDealerService.removeById(temp);
                channelCoopeCardealerService.remove(Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                        .eq(ChannelCoopeCardealerTemp::getChannelId, channelCoopeCardealerTemp.getChannelId())
                        .eq(ChannelCoopeCardealerTemp::getCardealerId, temp.getId())
                        .eq(ChannelCoopeCardealerTemp::getCardealerType, Constants.DIRECTCARDEALER)
                );
                channelMainBrandService.remove(Wrappers.<ChannelMainBrand>query().lambda()
                        .eq(ChannelMainBrand::getChannelId, temp.getId()));
                channelRiskInfoService.remove(Wrappers.<ChannelRiskInfoTemp>query().lambda()
                        .eq(ChannelRiskInfoTemp::getChannelId, temp.getId()));
                channelQuotaInfoService.remove(Wrappers.<ChannelQuotaInfoTemp>query().lambda()
                        .eq(ChannelQuotaInfoTemp::getChannelId, temp.getId()));
                channelAuthorizeRegionService.remove(Wrappers.<ChannelAuthorizeRegionTemp>query().lambda()
                        .eq(ChannelAuthorizeRegionTemp::getChannelId, temp.getId()));
                channelAuthorizeVehicleTempService.remove(Wrappers.<ChannelAuthorizeVehicleTemp>query().lambda()
                        .eq(ChannelAuthorizeVehicleTemp::getChannelId, temp.getId()));
                temp.setId(carDealerId);

                boolean newCar = enableDealerList.get(0).getChannelStatus() != null && enableDealerList.get(0).getChannelStatus() != "";
                boolean oldCar = enableDealerList.get(0).getChannelStatusOldCar() != null && enableDealerList.get(0).getChannelStatusOldCar() != "";
                if (newCar) {
                    temp.setChannelStatus(ENABLED);
                }
                if (oldCar) {
                    temp.setChannelStatusOldCar(ENABLED);
                }
                if (newCar && oldCar) {
                    temp.setBusinessType(Constants.BUSINESS_TYPE_NEW_CAR + "," + Constants.BUSINESS_TYPE_OLD_CAR);
                } else if (newCar && !oldCar) {
                    temp.setBusinessType(Constants.BUSINESS_TYPE_NEW_CAR);
                } else if (!newCar && oldCar) {
                    temp.setBusinessType(Constants.BUSINESS_TYPE_OLD_CAR);
                }

                directCarDealerService.updateById(temp);
                channelCoopeCardealerTemp.setCardealerId(temp.getId());
                boolean coopeResult = channelCoopeCardealerService.saveOrUpdate(channelCoopeCardealerTemp);
            } else {
                directCarDealerService.saveOrUpdate(temp);
            }
        } else {
            directCarDealerService.saveOrUpdate(temp);
        }

        //更新车商主营品牌
        channelMainBrandService.remove(Wrappers.<ChannelMainBrand>query().lambda()
                .eq(ChannelMainBrand::getChannelId, temp.getId())
                .eq(ChannelMainBrand::getChannelBelong, Constants.DIRECTCARDEALER)
        );

        List<ChannelMainBrand> channelMainBrandList = new ArrayList<>();
        if (mainBrand != null && mainBrand.length > 0) {
            for (String main : mainBrand) {
                ChannelMainBrand channelMainBrand = new ChannelMainBrand();
                String code = main.split(",")[0];
                String title = main.split(",")[1];
                String indeterminate = main.split(",")[2];
                String carLevel = main.split(",")[3];
                String spellCode = main.split(",")[4];
                channelMainBrand.setChannelId(temp.getId());
                channelMainBrand.setCode(code);
                channelMainBrand.setTitle(title);
                if (StrUtil.isNotBlank(indeterminate)) {
                    channelMainBrand.setIndeterminate(indeterminate);
                } else {
                    channelMainBrand.setIndeterminate("false");
                }
                if (StrUtil.isNotBlank(spellCode)) {
                    channelMainBrand.setSpellCode(spellCode);
                }
                channelMainBrand.setCarLevel(carLevel);
                channelMainBrand.setChannelBelong(Constants.DIRECTCARDEALER);
                channelMainBrandList.add(channelMainBrand);
            }
            // channelMainBrandService.saveOrUpdateBatch(channelMainBrandList);

            int size = channelMainBrandList.size();
            if (size <= 1000) {
                channelMainBrandService.saveBatch(channelMainBrandList);
            } else {
                for (int i = 0; i < size / 1000; i++) {
                    if (size / 1000 - i > 1) {
                        channelMainBrandService.saveBatch(channelMainBrandList.subList(1000 * i, 1000 * i + 999));
                    } else {
                        channelMainBrandService.saveBatch(channelMainBrandList.subList(1000 * i, size - 1));
                    }
                }
            }
        }
        directCarDealerConditionToCase.setMainBrandList(channelMainBrandList);
        //更新基本信息
        boolean basicResult = directCarDealerService.updateById(temp);
        if (!basicResult) {
            return IResponse.fail("车商基本信息更新失败");
        }
        list.add(temp);
        directCarDealerConditionToCase.setChannelBaseInfoTemp(temp);
        //更新合作商和车商关联
        channelCoopeCardealerTemp.setCardealerId(temp.getId());
        if ("channelAdmin".equals(channelCoopeCardealerTemp.getCreateBy())) {
            List<ChannelCoopeCardealerTemp> tempList = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                    .eq(ChannelCoopeCardealerTemp::getCardealerId, temp.getId())
                    .eq(ChannelCoopeCardealerTemp::getCardealerType, DIRECTCARDEALER)
            );
            if (CollectionUtil.isNotEmpty(tempList)) {
                for (ChannelCoopeCardealerTemp temp1 : tempList) {
                    temp1.setStatus(channelCoopeCardealerTemp.getStatus());
                    channelCoopeCardealerService.updateById(temp1);
                }
            }
        } else {
            List<ChannelCoopeCardealerTemp> coopeCardealerTempList = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                    .eq(ChannelCoopeCardealerTemp::getCardealerId, temp.getId())
                    .eq(ChannelCoopeCardealerTemp::getCardealerType, DIRECTCARDEALER)
                    .eq(ChannelCoopeCardealerTemp::getChannelId, channelCoopeCardealerTemp.getChannelId())
            );
            if (CollectionUtil.isNotEmpty(coopeCardealerTempList)) {
                for (ChannelCoopeCardealerTemp temp1 : coopeCardealerTempList) {
                    temp1.setStatus(channelCoopeCardealerTemp.getStatus());
                    channelCoopeCardealerService.updateById(temp1);
                }
            }
        }
        list.add(channelCoopeCardealerTemp);
      /*  if (!coopeResult) {
            return IResponse.fail("合作商和车商关联更新失败");
        }*/
        directCarDealerConditionToCase.setOldChannelId(condition.getOldChannelId());
        directCarDealerConditionToCase.setChannelCoopeCardealerTemp(channelCoopeCardealerTemp);


        /** 更新车商风控信息*/
        //判断当前登陆者是否拥有新车权限，由前端传入
        if (ChannelOnlineConstants.IS_HAVE_CAR_ROLE_YES.equals(condition.getIsNewCarRole())) {
            /** 保存渠道新车风控信息*/
            //渠道id赋值
            channelRiskInfoTemp.setChannelId(temp.getId());
            //清楚旧数据
            channelRiskInfoService.remove(Wrappers.<ChannelRiskInfoTemp>query().lambda()
                    .eq(ChannelRiskInfoTemp::getChannelId, temp.getId())
                    .eq(ChannelRiskInfoTemp::getBusinessType, Constants.BUSINESS_TYPE_NEW_CAR));
            channelRiskInfoService.saveOrUpdate(channelRiskInfoTemp);
            channelRiskInfoTempListToCase.add(channelRiskInfoTemp);

            /** 保存新车保证金信息前先清除旧的数据*/
            channelQuotaInfoService.remove(Wrappers.<ChannelQuotaInfoTemp>query().lambda()
                    .eq(ChannelQuotaInfoTemp::getChannelId, temp.getId())
                    .eq(ChannelQuotaInfoTemp::getBusinessType, Constants.BUSINESS_TYPE_NEW_CAR));
            //保存新车保证金信息
            for (ChannelQuotaInfoTemp quotaInfo : channelQuotaInfoList) {
                quotaInfo.setChannelId(temp.getId());
                //临时额度
                BigDecimal tempQuota = quotaInfo.getTempQuota() == null ? BigDecimal.ZERO : quotaInfo.getTempQuota();
                //签放额度
                BigDecimal quotaSigning = quotaInfo.getQuotaAmount() == null ? BigDecimal.ZERO : quotaInfo.getQuotaAmount();
                //剩余额度 = 临时额度+签放额度
                quotaInfo.setSurplusQuota(tempQuota.add(quotaSigning));
                //占用额度为0
                quotaInfo.setOccupiedQuota(BigDecimal.ZERO);
                channelQuotaInfoService.saveOrUpdate(quotaInfo);
                channelQuotaInfoTempsToCase.add(quotaInfo);
            }

            /** 保存渠道新车授权区域信息前先清除旧的数据*/
            channelAuthorizeRegionService.remove(Wrappers.<ChannelAuthorizeRegionTemp>query().lambda()
                    .eq(ChannelAuthorizeRegionTemp::getChannelId, temp.getId())
                    .eq(ChannelAuthorizeRegionTemp::getBusinessType, Constants.BUSINESS_TYPE_NEW_CAR));
            //保存渠道新车授权区域
            List<ChannelAuthorizeRegionTemp> channelAuthorizeRegionTempList = new ArrayList<>();
            if (mainArea != null && mainArea.length > 0) {
                for (String area : mainArea) {
                    ChannelAuthorizeRegionTemp regionTemp = new ChannelAuthorizeRegionTemp();
                    String code = area.split(",")[0];
                    String title = area.split(",")[1];
                    String isParent = area.split(",")[2];
                    String parentId = area.split(",")[3];
                    regionTemp.setChannelId(temp.getId());
                    regionTemp.setCode(code);
                    regionTemp.setTitle(title);
                    regionTemp.setIsParent(isParent);
                    regionTemp.setParentId(parentId);
                    regionTemp.setBusinessType(Constants.BUSINESS_TYPE_NEW_CAR);
                    channelAuthorizeRegionTempList.add(regionTemp);
                }
                int size = channelAuthorizeRegionTempList.size();
                if (size <= 1000) {
                    channelAuthorizeRegionService.saveOrUpdateBatch(channelAuthorizeRegionTempList);
                } else {
                    for (int i = 0; i < size / 1000; i++) {
                        if (size / 1000 - i > 1) {
                            channelAuthorizeRegionService.saveOrUpdateBatch(channelAuthorizeRegionTempList.subList(1000 * i, 1000 * i + 999));
                        } else {
                            channelAuthorizeRegionService.saveOrUpdateBatch(channelAuthorizeRegionTempList.subList(1000 * i, size - 1));
                        }
                    }
                }
                /*for(ChannelAuthorizeRegionTemp regionTemp : channelAuthorizeRegionTempList){
                    channelAuthorizeRegionService.saveOrUpdateBatch(regionTemp);
                }*/
                ChannelAuthorizeRegionTempsToCase.addAll(channelAuthorizeRegionTempList);
            }

            /** 保存渠道授权车型信息前先清除旧的数据*/
            channelAuthorizeVehicleTempService.remove(Wrappers.<ChannelAuthorizeVehicleTemp>query().lambda()
                    .eq(ChannelAuthorizeVehicleTemp::getChannelId, temp.getId())
                    .eq(ChannelAuthorizeVehicleTemp::getBusinessType, Constants.BUSINESS_TYPE_NEW_CAR));
            //保存渠道新车授权车型
            List<ChannelAuthorizeVehicleTemp> channelAuthorizeVehicleList = new ArrayList<>();
            if (mainCar != null && mainCar.length > 0) {
                for (String main : mainCar) {
                    ChannelAuthorizeVehicleTemp channelAuthorizeVehicleTemp = new ChannelAuthorizeVehicleTemp();
                    String code = main.split(",")[0];
                    String title = main.split(",")[1];
                    String parentId = main.split(",")[2];
                    String indeterminate = main.split(",")[3];
                    String carLevel = main.split(",")[4];
                    String spellCode = main.split(",")[5];
                    String carType = main.split(",")[6];

                    channelAuthorizeVehicleTemp.setChannelId(temp.getId());
                    channelAuthorizeVehicleTemp.setCode(code);
                    channelAuthorizeVehicleTemp.setTitle(title);
                    channelAuthorizeVehicleTemp.setParentId(parentId);
                    channelAuthorizeVehicleTemp.setCarLevel(carLevel);
                    if("null".equals(carType)){
                        channelAuthorizeVehicleTemp.setCarType("");
                    }else{
                        channelAuthorizeVehicleTemp.setCarType(carType);
                    }
                    if (StrUtil.isNotBlank(indeterminate)) {
                        channelAuthorizeVehicleTemp.setIndeterminate(indeterminate);
                    } else {
                        channelAuthorizeVehicleTemp.setIndeterminate("false");
                    }
                    if (StrUtil.isNotBlank(spellCode)) {
                        channelAuthorizeVehicleTemp.setSpellCode(spellCode);
                    }
                    channelAuthorizeVehicleTemp.setBusinessType(Constants.BUSINESS_TYPE_NEW_CAR);
                    channelAuthorizeVehicleList.add(channelAuthorizeVehicleTemp);
                }
               /* for(ChannelAuthorizeVehicleTemp vehicleTemp : channelAuthorizeVehicleList){
                    channelAuthorizeVehicleTempService.saveOrUpdate(vehicleTemp);
                }*/
                int size = channelAuthorizeVehicleList.size();
                if (size <= 1000) {
                    channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList);
                } else {
                    for (int i = 0; i < size / 1000; i++) {
                        if (size / 1000 - i > 1) {
                            channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList.subList(1000 * i, 1000 * i + 999));
                        } else {
                            channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList.subList(1000 * i, size - 1));
                        }
                    }
                }
                // channelAuthorizeVehicleTempService.saveOrUpdateBatch(channelAuthorizeVehicleList);
                ChannelAuthorizeVehicleTempsToCase.addAll(channelAuthorizeVehicleList);
            }
        }


        //判断当前登陆者是否拥有二手车权限，由前端传入
        if (ChannelOnlineConstants.IS_HAVE_CAR_ROLE_YES.equals(condition.getIsOldCarRole())) {
            //渠道id赋值
            channelRiskInfoTempOld.setChannelId(temp.getId());
            //二手车风控信息查询判断
            channelRiskInfoService.remove(Wrappers.<ChannelRiskInfoTemp>query().lambda()
                    .eq(ChannelRiskInfoTemp::getChannelId, temp.getId())
                    .eq(ChannelRiskInfoTemp::getBusinessType, Constants.BUSINESS_TYPE_OLD_CAR));
            channelRiskInfoService.saveOrUpdate(channelRiskInfoTempOld);
            channelRiskInfoTempListToCase.add(channelRiskInfoTempOld);
            // directCarDealerConditionToCase.setChannelRiskInfoList(channelRiskInfoTempListToCase);

            list.add(channelRiskInfoTemp);

            /** 保存渠道二手车保证金信息前先清除旧的数据*/
            channelQuotaInfoService.remove(Wrappers.<ChannelQuotaInfoTemp>query().lambda()
                    .eq(ChannelQuotaInfoTemp::getChannelId, temp.getId())
                    .eq(ChannelQuotaInfoTemp::getBusinessType, Constants.BUSINESS_TYPE_OLD_CAR));
            //保存二手车保证金信息
            for (ChannelQuotaInfoTemp quotaInfo : channelQuotaInfoListOld) {
                quotaInfo.setChannelId(temp.getId());
                //临时额度
                BigDecimal tempQuota = quotaInfo.getTempQuota() == null ? BigDecimal.ZERO : quotaInfo.getTempQuota();
                //签放额度
                BigDecimal quotaSigning = quotaInfo.getQuotaAmount() == null ? BigDecimal.ZERO : quotaInfo.getQuotaAmount();
                //剩余额度 = 临时额度+签放额度
                quotaInfo.setSurplusQuota(tempQuota.add(quotaSigning));
                //占用额度为0
                quotaInfo.setOccupiedQuota(BigDecimal.ZERO);

                channelQuotaInfoService.saveOrUpdate(quotaInfo);
                channelQuotaInfoTempsToCase.add(quotaInfo);
            }

            /** 保存渠道二手车授权区域信息前先清除旧的数据*/
            channelAuthorizeRegionService.remove(Wrappers.<ChannelAuthorizeRegionTemp>query().lambda()
                    .eq(ChannelAuthorizeRegionTemp::getChannelId, temp.getId())
                    .eq(ChannelAuthorizeRegionTemp::getBusinessType, Constants.BUSINESS_TYPE_OLD_CAR));
            //保存渠道二手车授权区域
            List<ChannelAuthorizeRegionTemp> channelAuthorizeRegionTempList = new ArrayList<>();
            if (mainAreaOld != null && mainAreaOld.length > 0) {
                for (String area : mainAreaOld) {
                    ChannelAuthorizeRegionTemp regionTemp = new ChannelAuthorizeRegionTemp();
                    String code = area.split(",")[0];
                    String title = area.split(",")[1];
                    String isParent = area.split(",")[2];
                    String parentId = area.split(",")[3];
                    regionTemp.setChannelId(temp.getId());
                    regionTemp.setCode(code);
                    regionTemp.setTitle(title);
                    regionTemp.setIsParent(isParent);
                    regionTemp.setParentId(parentId);
                    regionTemp.setBusinessType(Constants.BUSINESS_TYPE_OLD_CAR);
                    channelAuthorizeRegionTempList.add(regionTemp);
                }
                /*for(ChannelAuthorizeRegionTemp regionTemp : channelAuthorizeRegionTempList){
                    channelAuthorizeRegionService.saveOrUpdate(regionTemp);
                }*/
                int size = channelAuthorizeRegionTempList.size();
                if (size <= 1000) {
                    channelAuthorizeRegionService.saveBatch(channelAuthorizeRegionTempList);
                } else {
                    for (int i = 0; i < size / 1000; i++) {
                        if (size / 1000 - i > 1) {
                            channelAuthorizeRegionService.saveBatch(channelAuthorizeRegionTempList.subList(1000 * i, 1000 * i + 999));
                        } else {
                            channelAuthorizeRegionService.saveBatch(channelAuthorizeRegionTempList.subList(1000 * i, size - 1));
                        }
                    }
                }
                // channelAuthorizeRegionService.saveOrUpdateBatch(channelAuthorizeRegionTempList);
                ChannelAuthorizeRegionTempsToCase.addAll(channelAuthorizeRegionTempList);
            }

            /** 保存渠道授权车型信息前先清除旧的数据*/
            channelAuthorizeVehicleTempService.remove(Wrappers.<ChannelAuthorizeVehicleTemp>query().lambda()
                    .eq(ChannelAuthorizeVehicleTemp::getChannelId, temp.getId())
                    .eq(ChannelAuthorizeVehicleTemp::getBusinessType, Constants.BUSINESS_TYPE_OLD_CAR));

            //保存渠道二手车授权车型
            List<ChannelAuthorizeVehicleTemp> channelAuthorizeVehicleList = new ArrayList<>();
            if (mainCarOld != null && mainCarOld.length > 0) {
                for (String main : mainCarOld) {
                    ChannelAuthorizeVehicleTemp channelAuthorizeVehicleTemp = new ChannelAuthorizeVehicleTemp();
                    String code = main.split(",")[0];
                    String title = main.split(",")[1];
                    String indeterminate = main.split(",")[3];
                    String carLevel = main.split(",")[4];
                    String spellCode = main.split(",")[5];
                    String carType = main.split(",")[6];
                    String parentId = main.split(",")[2];
                    channelAuthorizeVehicleTemp.setChannelId(temp.getId());
                    channelAuthorizeVehicleTemp.setCode(code);
                    channelAuthorizeVehicleTemp.setTitle(title);
                    channelAuthorizeVehicleTemp.setParentId(parentId);
                    channelAuthorizeVehicleTemp.setCarLevel(carLevel);
                     if("null".equals(carType)){
                        channelAuthorizeVehicleTemp.setCarType("");
                    }else{
                        channelAuthorizeVehicleTemp.setCarType(carType);
                    }
                    if (StrUtil.isNotBlank(indeterminate)) {
                        channelAuthorizeVehicleTemp.setIndeterminate(indeterminate);
                    } else {
                        channelAuthorizeVehicleTemp.setIndeterminate("false");
                    }
                    if (StrUtil.isNotBlank(spellCode)) {
                        channelAuthorizeVehicleTemp.setSpellCode(spellCode);
                    }
                    channelAuthorizeVehicleTemp.setBusinessType(Constants.BUSINESS_TYPE_OLD_CAR);
                    channelAuthorizeVehicleList.add(channelAuthorizeVehicleTemp);
                }
                /*for(ChannelAuthorizeVehicleTemp vehicleTemp : channelAuthorizeVehicleList){
                    channelAuthorizeVehicleTempService.saveOrUpdate(vehicleTemp);
                }*/
                int size = channelAuthorizeVehicleList.size();
                if (size <= 1000) {
                    channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList);
                } else {
                    for (int i = 0; i < size / 1000; i++) {
                        if (size / 1000 - i > 1) {
                            channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList.subList(1000 * i, 1000 * i + 999));
                        } else {
                            channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList.subList(1000 * i, size - 1));
                        }
                    }
                }
                // channelAuthorizeVehicleTempService.saveOrUpdateBatch(channelAuthorizeVehicleList);
                ChannelAuthorizeVehicleTempsToCase.addAll(channelAuthorizeVehicleList);
            }
        }

        directCarDealerConditionToCase.setChannelRiskInfoList(channelRiskInfoTempListToCase);
        directCarDealerConditionToCase.setChannelQuotaInfoTempList(channelQuotaInfoTempsToCase);
        directCarDealerConditionToCase.setChannelAuthorizeVehicleList(ChannelAuthorizeVehicleTempsToCase);
        directCarDealerConditionToCase.setChannelAuthorizeRegionList(ChannelAuthorizeRegionTempsToCase);

        //如果状态为00,启用 则同步到案件服务
        if (ENABLED.equals(temp.getChannelStatus()) || ENABLED.equals(temp.getChannelStatusOldCar())) {
            saveDirectCarDealerInfoToCase(temp.getId(), directCarDealerConditionToCase);
        }


        //审核中的状态走这里
        if (Constants.REVIEW.equals(channelCoopeCardealerTemp.getStatus())) {
            List<Object> workfolwList = new ArrayList<>();
            workfolwList.add(temp);
            workfolwList.add(channelCoopeCardealerTemp);
            directCarDealerWorkflow(workfolwList);
        }

        return IResponse.success(list);
    }


    //保存开票账号信息
    @PostMapping("/savaInvoiceInfo")
    @ApiOperation(value = "保存开票信息")
    public IResponse savaInvoiceInfo(@RequestBody DirectCarDealerCondition condition) {

        DirectCarDealer directCarDealer = directCarDealerService.getById(condition.getId());
        directCarDealer.setTaxpayerType(condition.getTaxpayerType());
        directCarDealer.setTaxpayerIdNumber(condition.getTaxpayerIdNumber());
        directCarDealer.setInvoiceTelNumber(condition.getInvoiceTelNumber());
        directCarDealer.setInvoiceAddress(condition.getInvoiceAddress());
        directCarDealer.setOpeningBank(condition.getOpeningBank());
        directCarDealer.setBankAccount(condition.getBankAccount());
        directCarDealer.setTaxRate(condition.getTaxRate());

        boolean result = directCarDealerService.updateById(directCarDealer);
        return result ? IResponse.success("成功") : IResponse.fail("失败");
    }


    @Transactional
    @RequestMapping(value = "/saveAccountInfo", method = RequestMethod.POST)
    @CacheEvict(value = "channel_receivables_account_temp", allEntries = true)
    @ApiOperation(value = "保存收款账号数据")
    public IResponse saveAccountInfo(@Valid @RequestBody ChannelAccountInfoCondition condition) throws ParseException {
        ChannelReceivablesAccountTemp temp = condition.getChannelReceivablesAccountTemp();

        List<ChannelReceivablesAccountTemp> list = channelAccountInfoService.list(Wrappers.<ChannelReceivablesAccountTemp>query().lambda()
                .eq(ChannelReceivablesAccountTemp::getChannelId, temp.getChannelId())
                .eq(ChannelReceivablesAccountTemp::getAccountAttribute, temp.getAccountAttribute())
                .eq(ChannelReceivablesAccountTemp::getCollectionType, temp.getCollectionType())
                .eq(ChannelReceivablesAccountTemp::getStatus, Constants.DRAFT)

        );
        if (list.size() > 0) {
            return IResponse.fail("已存在草稿状态的同类型账号");
        }

        boolean saveResult = channelAccountInfoService.saveOrUpdate(temp);
        return saveResult ? IResponse.success(Boolean.TRUE).setMsg("录入成功") : IResponse.fail("录入失败！");

    }

    /**
     * 收款账号修改
     *
     * @param condition
     * @return
     * @throws ParseException
     */
    @Transactional
    @RequestMapping(value = "/updateAccountInfo", method = RequestMethod.POST)
    @CacheEvict(value = "channel_receivables_account_temp", allEntries = true)
    @ApiOperation(value = "修改收款账号数据")
    public IResponse updateAccountInfo(@Valid @RequestBody ChannelAccountInfoCondition condition) throws ParseException {

        List<ChannelReceivablesAccountTemp> list = channelAccountInfoService.list(Wrappers.<ChannelReceivablesAccountTemp>query().lambda()
                .eq(ChannelReceivablesAccountTemp::getChannelId, condition.getChannelId())
                .eq(ChannelReceivablesAccountTemp::getAccountAttribute, condition.getAccountAttribute())
                .eq(ChannelReceivablesAccountTemp::getCollectionType, condition.getCollectionType())
                .eq(ChannelReceivablesAccountTemp::getStatus, Constants.DRAFT)
                .ne(ChannelReceivablesAccountTemp::getId, condition.getId())
        );
        if (list.size() > 0) {
            return IResponse.fail("已存在草稿状态的同类型账号");
        }

        boolean result = channelAccountInfoService.updateById(condition);

        return result ? IResponse.success(Boolean.TRUE).setMsg("录入成功") : IResponse.fail("录入失败！");
    }


    @GetMapping("/findAllCustomerManager")
    @ApiOperation(value = "查询所有的城市经理")
    public IResponse findAllCustomerManager() {
        List<DirectCarDealer> listDirectCarDealer = directCarDealerService.list(Wrappers.<DirectCarDealer>query().lambda().eq(DirectCarDealer::getChannelType, Constants.DIRECTCARDEALER));
        Set customerManagers = new HashSet();
        List<ChannelRiskInfoTemp> list = new ArrayList<>();

        for (DirectCarDealer dealer : listDirectCarDealer) {
            List<ChannelRiskInfoTemp> list1 = channelRiskInfoService.list(Wrappers.<ChannelRiskInfoTemp>query().lambda().eq(ChannelRiskInfoTemp::getChannelId, dealer.getId()));
            list.addAll(list1);
        }

        for (ChannelRiskInfoTemp riskInfoTemp : list) {
            customerManagers.add(riskInfoTemp.getCustomerManager());
        }
        return IResponse.success(customerManagers);
    }

    @PostMapping("/bulkEditingCustomerManager")
    @Transactional
    @ApiOperation(value = "批量修改直营车商城市经理")
    public IResponse bulkEditingCustomerManager(@RequestBody ChangeSalesmanCondition condition) {

        Long channelId = condition.getChannelId();
        String type = condition.getBusinessType();
        ArrayList<Long> ids = condition.getAllCarDealerIds();
        String customerManager = condition.getSalesman();
        if (ids == null || channelId == null || customerManager == null || type == null) {
            return IResponse.fail("参数为空").setData(null);
        }
        boolean result = true;
        for (int i = 0; i < ids.size(); i++) {
            //改风控表里的城市经理
            List<ChannelRiskInfoTemp> riskList = channelRiskInfoService.list(Wrappers.<ChannelRiskInfoTemp>query().lambda()
                    .eq(ChannelRiskInfoTemp::getChannelId, ids.get(i))
                    .eq(ChannelRiskInfoTemp::getBusinessType, type));
            if (riskList != null && riskList.size() > 0) {
                for (ChannelRiskInfoTemp risk : riskList) {
                    risk.setCustomerManager(customerManager);
                }
                result = channelRiskInfoService.updateBatchById(riskList);
                //改车商合作商中间表里的关联账户
                List<ChannelCoopeCardealerTemp> list = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                        .eq(ChannelCoopeCardealerTemp::getCardealerId, ids.get(i))
                        .eq(ChannelCoopeCardealerTemp::getChannelId, channelId)
                        .eq(ChannelCoopeCardealerTemp::getCardealerType, Constants.DIRECTCARDEALER)
                );
                if (list.size() > 0) {
                    ChannelCoopeCardealerTemp coopeCardealerTemp = list.get(0);
                    if (Constants.BUSINESS_TYPE_NEW_CAR.equals(type)) {
                        coopeCardealerTemp.setAssociAccount(customerManager);
                    } else {
                        coopeCardealerTemp.setAssociAccountOld(customerManager);
                    }
                    boolean result2 = channelCoopeCardealerService.updateById(coopeCardealerTemp);
                    if (!result2 || !result) {
                        return IResponse.fail("修改失败");
                    }
                }
            }

            //改case中的数据
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("clientId", channelConfig.getCaseClientId());
            headers.put("clientSecret", channelConfig.getCaseClientSecret());
            channelUseCaseService.bulkEditingCustomerManager(condition, headers);
        }
        return IResponse.success("修改成功");
    }


    @GetMapping("/getAllSPChannels")
    @ApiOperation(value = "查询所有的SP和总对总")
    public IResponse getAllSP() {
        List list = new ArrayList();
        list.add(Constants.SP);
        list.add(Constants.TOTAl);
        QueryWrapper<ChannelBaseInfoTemp> channelBaseInfoTempQueryWrapper = new QueryWrapper<>();
        channelBaseInfoTempQueryWrapper.eq("channel_type", Constants.CHANNEL);
        channelBaseInfoTempQueryWrapper.in("channel_belong", list);
        channelBaseInfoTempQueryWrapper.and(wrapper -> wrapper.eq("channel_status", ENABLED).or().eq("channel_status_old_car", ENABLED));
        List<ChannelBaseInfoTemp> channelBaseInfos = channelOnlineService.list(channelBaseInfoTempQueryWrapper);
        return IResponse.success(channelBaseInfos);
    }

    @GetMapping("/getAllDirectChannels")
    @ApiOperation(value = "查询所有直营渠道")
    public IResponse getAllChannels() {
        QueryWrapper<ChannelBaseInfoTemp> channelBaseInfoTempQueryWrapper = new QueryWrapper<>();
        channelBaseInfoTempQueryWrapper.eq("channel_type", Constants.CHANNEL);
        channelBaseInfoTempQueryWrapper.eq("channel_belong", Constants.DIRECT);
        channelBaseInfoTempQueryWrapper.and(wrapper -> wrapper.eq("channel_status", ENABLED).or().eq("channel_status_old_car", ENABLED));
        List<ChannelBaseInfoTemp> channelBaseInfos = channelOnlineService.list(channelBaseInfoTempQueryWrapper);
        return IResponse.success(channelBaseInfos);
    }


    @PostMapping("/updateCommonCarDealerStatus")
    @ApiOperation(value = "更新普通车商状态")
    @Transactional(rollbackFor = Exception.class)
    public IResponse updateCommonCarDealerStatus(@RequestBody CarDealerCondition condition) {
        boolean updateResult = carDealerService.updateById(condition.getCommonCarDealer());
        boolean updateResult2 = channelCoopeCardealerService.update(condition.getChannelCoopeCardealerTemp(), Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                .eq(ChannelCoopeCardealerTemp::getCardealerId, condition.getCommonCarDealer().getId())
                .eq(ChannelCoopeCardealerTemp::getChannelId, condition.getChannelCoopeCardealerTemp().getChannelId())
                .eq(ChannelCoopeCardealerTemp::getCardealerType, Constants.COMMONCARDEALER)
        );
        if (updateResult && updateResult2) {
            return IResponse.success("操作成功");
        }
        return IResponse.fail("操作失败");
    }


    @PostMapping("/getCarDealersByChannelId")
    @ApiOperation(value = "根据渠道id获取对应的车商")
    public IResponse getCarDealersByChannelId(@RequestBody CarDealerCondition condition) {
        List<CommonCarDealerVo> commonList = new ArrayList<>();
        Long channelId = condition.getChannelId();
        //获取渠道信息
        DirectCarDealer channel = directCarDealerService.getById(channelId);
        String channelBelong = channel.getChannelBelong();
        List<String> status = new ArrayList<>();
        status.add(ENABLED);
        status.add(DISABLE);

        if (Constants.SP.equals(channelBelong) || Constants.TOTAl.equals(channelBelong)) {
            //sp和总对总查普通车商表
            Page page = channelCoopeCardealerService.page(new Page(condition.getPageNumber(), condition.getPageSize()), Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                    .eq(ChannelCoopeCardealerTemp::getChannelId, channelId)
                    .eq(ChannelCoopeCardealerTemp::getCardealerType, Constants.COMMONCARDEALER)
                    .in(ChannelCoopeCardealerTemp::getStatus, status)
            );
            List<ChannelCoopeCardealerTemp> commonTemps = page.getRecords();
            int totalSize = 0;
            if (commonTemps != null && commonTemps.size() > 0) {
                for (ChannelCoopeCardealerTemp coopeCardealerTemp : commonTemps) {
                    CommonCarDealerVo commonCarDealerVo = new CommonCarDealerVo();
                    String title = "";
                    //去普通车商表里查
                    CommonCarDealer commonCarDealer = carDealerService.getById(coopeCardealerTemp.getCardealerId());
                    if (commonCarDealer != null) {
                        List<ChannelMainBrand> brandList = channelMainBrandService.list(Wrappers.<ChannelMainBrand>query().lambda()
                                .eq(ChannelMainBrand::getChannelId, commonCarDealer.getId())
                                .eq(ChannelMainBrand::getChannelBelong, Constants.COMMONCARDEALER)
                        );
                        if (brandList.size() > 0 && brandList != null) {
                            for (ChannelMainBrand brand : brandList) {
                                title += brand.getTitle() + ",";
                            }
                        }
                        commonCarDealerVo.setCardealerName(commonCarDealer.getCardealerName());
                        commonCarDealerVo.setChannelFullName(channel.getChannelFullName());
                        commonCarDealerVo.setCorporateName(commonCarDealer.getCorporateName());
                        commonCarDealerVo.setTelephoneNumber(commonCarDealer.getTelephoneNumber());
                        commonCarDealerVo.setCardealerProperties(commonCarDealer.getCardealerProperties());
                        commonCarDealerVo.setSalesMan(coopeCardealerTemp.getAssociAccount());
                        commonCarDealerVo.setRegistrationTime(commonCarDealer.getRegistrationTime());
                        commonCarDealerVo.setSocUniCrtCode(commonCarDealer.getSocUniCrtCode());
                        commonCarDealerVo.setAddress(commonCarDealer.getAddress());
                        commonCarDealerVo.setStatus(coopeCardealerTemp.getStatus());
                        commonCarDealerVo.setId(commonCarDealer.getId());
                        commonCarDealerVo.setMainBrand(title);
                        commonCarDealerVo.setChannelBelong(channelBelong);
                        commonList.add(commonCarDealerVo);
                        totalSize++;
                    }
                }
            }
            page.setRecords(commonList);
            page.setTotal(totalSize);
            return IResponse.success(page);
        } else if (Constants.DIRECT.equals(channelBelong)) {
            Page page = channelCoopeCardealerService.page(new Page(condition.getPageNumber(), condition.getPageSize()), Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                    .eq(ChannelCoopeCardealerTemp::getChannelId, channelId)
                    .eq(ChannelCoopeCardealerTemp::getCardealerType, Constants.DIRECTCARDEALER)
                    .in(ChannelCoopeCardealerTemp::getStatus, status)
            );
            List<ChannelCoopeCardealerTemp> directTemps = page.getRecords();
            int totalSize = 0;
            if (directTemps != null && directTemps.size() > 0) {
                for (ChannelCoopeCardealerTemp coopeCardealerTemp : directTemps) {
                    CommonCarDealerVo commonCarDealerVo = new CommonCarDealerVo();
                    String title = "";
                    //去直营车商表里查
                    DirectCarDealer directCarDealer = directCarDealerService.getById(coopeCardealerTemp.getCardealerId());
                    if (directCarDealer != null) {
                        List<ChannelMainBrand> brandList = channelMainBrandService.list(Wrappers.<ChannelMainBrand>query().lambda()
                                .eq(ChannelMainBrand::getChannelId, directCarDealer.getId())
                                .eq(ChannelMainBrand::getChannelBelong, Constants.DIRECTCARDEALER)
                        );
                        if (brandList.size() > 0 && brandList != null) {
                            for (ChannelMainBrand brand : brandList) {
                                title += brand.getTitle() + ",";
                            }
                        }
                        commonCarDealerVo.setCardealerName(directCarDealer.getChannelFullName());
                        commonCarDealerVo.setChannelFullName(channel.getChannelFullName());
                        commonCarDealerVo.setCorporateName(directCarDealer.getLegalPerson());
                        commonCarDealerVo.setTelephoneNumber(directCarDealer.getLegalPersonTel());
                        commonCarDealerVo.setCardealerProperties(directCarDealer.getCarDealType());
                        commonCarDealerVo.setSalesMan(coopeCardealerTemp.getAssociAccount());
                        commonCarDealerVo.setRegistrationTime(directCarDealer.getRegistrationDate());
                        commonCarDealerVo.setSocUniCrtCode(directCarDealer.getSocUniCrtCode());
                        commonCarDealerVo.setAddress(directCarDealer.getChannelAddress());
                        commonCarDealerVo.setStatus(coopeCardealerTemp.getStatus());
                        commonCarDealerVo.setId(directCarDealer.getId());
                        commonCarDealerVo.setMainBrand(title);
                        commonCarDealerVo.setChannelBelong(channelBelong);
                        commonList.add(commonCarDealerVo);
                        totalSize++;
                    }
                }
            }
            page.setRecords(commonList);
            page.setTotal(totalSize);
            return IResponse.success(page);
        }
        return IResponse.fail("查询失败");

    }

    @PostMapping(value = "/getAreaListCondition")
    @ApiOperation(value = "多条件分页获取直营车商展业")
    public IResponse getAreaListCondition(@RequestBody DirectCarDealerCondition condition) {
        Page page = new Page(condition.getPageNumber(), condition.getPageSize());
        IPage<DirectCarDealerVo> directCarDealerList = carDealerService.getAreaListCondition(page, condition);
        return IResponse.success(directCarDealerList);
    }

    @PostMapping("/getCarDealerListByCode")
    @ApiOperation(value = "多条件分页根据车商代码获取普通车商")
    public IResponse<IPage<CommonCarDealerVo>> getCarDealerListByCode(@RequestBody CarDealerCondition carDealerCondition) {
        Page page = new Page(carDealerCondition.getPageNumber(), carDealerCondition.getPageSize());
        IPage<CommonCarDealerVo> list = mapper.getCarDealerListByCode(page, carDealerCondition);
        return IResponse.success(list);
    }


    @GetMapping(value = "/changeAccountStatus/{channelId}")
    @ApiOperation(value = "启用车商收款账号")
    public IResponse changeAccountStatus(@PathVariable String channelId) {
        List<ChannelReceivablesAccountTemp> accountTemps = channelAccountInfoService.list(Wrappers.<ChannelReceivablesAccountTemp>query().lambda()
                .eq(ChannelReceivablesAccountTemp::getChannelId, channelId));
        if (accountTemps != null && accountTemps.size() > 0) {
            for (ChannelReceivablesAccountTemp temp : accountTemps) {
                temp.setStatus(ENABLED);
            }
            channelAccountInfoService.updateBatchById(accountTemps);
        } else {
            return IResponse.fail("请先保存收款账号信息");
        }
        return IResponse.success(accountTemps);
    }

    /**
     * 下面的接口都是给进件服务车商用的
     */

    @RequestMapping(value = "/getAccountInfo", method = RequestMethod.POST)
    @ApiOperation(value = "多条件分页获取收款账号信息")
    public IResponse getAccountInfo(@RequestBody DirectCarDealerCondition condition) {
        //渠道id为空null
        if (StringUtils.isBlank(condition.getChannelId())) {
            return IResponse.fail("渠道id不能为空");
        }
        IPage<ChannelReceivablesAccountTemp> list = channelAccountInfoService.page(new Page(condition.getPageNumber(), condition.getPageSize())
                , Wrappers.<ChannelReceivablesAccountTemp>query().lambda()
                        .eq(StringUtils.isNotEmpty(condition.getChannelId()), ChannelReceivablesAccountTemp::getChannelId, condition.getChannelId()));
        return IResponse.success(list);
    }

    //查询接口

    @GetMapping("/disableCarDealerFromApply/{ids}/{channelId}/{status}")
    @ApiOperation(value = "停用进件端普通车商")
    @Transactional(rollbackFor = Exception.class)
    public IResponse disableCarDealerFromApply(@PathVariable String[] ids, @PathVariable String channelId, @PathVariable String status) {
        if (ids == null || channelId == null) {
            return IResponse.fail("参数为空");
        }
        for (int i = 0; i < ids.length; i++) {
            //更新中间表
            List<ChannelCoopeCardealerTemp> coopeCardealers = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                    .eq(ChannelCoopeCardealerTemp::getCardealerId, ids[i])
                    .eq(ChannelCoopeCardealerTemp::getChannelId, channelId)
                    .eq(ChannelCoopeCardealerTemp::getCardealerType, Constants.COMMONCARDEALER));
            if (coopeCardealers != null && coopeCardealers.size() > 0) {
                if (coopeCardealers != null && coopeCardealers.size() > 0) {
                    for (ChannelCoopeCardealerTemp coopeCardealer : coopeCardealers) {
                        coopeCardealer.setStatus(status);
                    }
                }
                boolean update = channelCoopeCardealerService.updateBatchById(coopeCardealers);
                if (!update) {
                    return IResponse.fail("停用失败");
                }
            }
        }
       /* //调用案件服务停用车商
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("clientId", channelConfig.getCaseClientId());
        headers.put("clientSecret", channelConfig.getCaseClientSecret());
        Assert.isTrue((boolean) channelUseCaseService.disableCarDealerFromCase(ids, channelId,status, headers).getData(), "操作失败,请重试!");
*/
        CarDealerCondition carDealerCondition = new CarDealerCondition();
        carDealerCondition.setMqTypeEnum(MqTypeEnum.change_status);
        carDealerCondition.setIds(ids);
        carDealerCondition.setChannelId(Long.parseLong(channelId));
        carDealerCondition.setStatus(status);
        AfsTransEntity<CarDealerCondition> entity = senderChannelToCaseImpl.sendCommonCarDealerToCase(carDealerCondition);
        senderChannelToCase.sendCommonCarDealerToCase(entity);
        return IResponse.success("停用成功");
    }

    @GetMapping("/bulkEditingSalesmanFromApply/{salesman}/{ids}/{channelId}")
    @ApiOperation(value = "进件端批量修改业务员")
    public IResponse bulkEditingSalesmanFromApply(@PathVariable String salesman, @PathVariable String[] ids, @PathVariable String channelId) {
        if (ids == null || salesman == null || channelId == null) {
            return IResponse.fail("参数为空");
        }
        for (int i = 0; i < ids.length; i++) {
            List<ChannelCoopeCardealerTemp> list = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                    .eq(ChannelCoopeCardealerTemp::getCardealerId, ids[i])
                    .eq(ChannelCoopeCardealerTemp::getChannelId, channelId)
                    .eq(ChannelCoopeCardealerTemp::getCardealerType, Constants.COMMONCARDEALER)
            );
            if (list.size() > 0 && list != null) {
                for (ChannelCoopeCardealerTemp temp : list) {
                    temp.setAssociAccount(salesman);
                }
            }
            boolean result2 = channelCoopeCardealerService.updateBatchById(list);
            if (!result2) {
                return IResponse.fail("修改失败");
            }
        }
        return IResponse.success("修改成功");
    }

    @DeleteMapping("/deleteCommonCardealerByIdFromApply/{id}/{channelId}")
    @ApiOperation(value = "删除进件端普通车商")
    public IResponse deleteCommonCardealerById(@PathVariable String id, @PathVariable String channelId) {
        //删关联表
        boolean remove = channelCoopeCardealerService.remove(Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                .eq(ChannelCoopeCardealerTemp::getCardealerId, id)
                .eq(ChannelCoopeCardealerTemp::getChannelId, channelId)
                .eq(ChannelCoopeCardealerTemp::getCardealerType, Constants.COMMONCARDEALER)
        );
        return remove ? IResponse.success("删除成功") : IResponse.fail("删除失败");
    }

    @GetMapping("/getAllSaleManByChannelId/{channelId}/{businessType}")
    @ApiOperation(value = "根据渠道id获取所有业务员")
    public IResponse getAllSaleManByChannelId(@PathVariable String channelId, @PathVariable String businessType) {

        Map<String, String> headers = new HashMap<String, String>();
        headers.put("clientId", channelConfig.getApplyAdminClientId());
        headers.put("clientSecret", channelConfig.getApplyAdminClientSecret());
        return adminService.getAllSaleManByChannelId(channelId, businessType, headers);

    }


    @GetMapping("/getAreaByChannelId/{channelId}/{businessType}")
    @ApiOperation(value = "根据渠道id获取授权区域")
    public IResponse getAreaByChannelId(@PathVariable String channelId, @PathVariable String businessType) {

        List<TsysAddressParam> list2 = tsysAddressParamService.list(Wrappers.<TsysAddressParam>query().lambda().orderByAsc(TsysAddressParam::getValue));
        List<TsysAddressParam> list = new ArrayList<>();

        List<ChannelRiskInfoTemp> riskInfoTemps = channelRiskInfoService.list(Wrappers.<ChannelRiskInfoTemp>query().lambda()
                .eq(ChannelRiskInfoTemp::getChannelId, channelId)
                .eq(ChannelRiskInfoTemp::getBusinessType, businessType)
        );
        if (riskInfoTemps.size() > 0) {
            if (Constants.AUTH_REGION_SWITCH_OFF.equals(riskInfoTemps.get(0).getAuthRegionSwitch())) {
                list.addAll(list2);
            } else {
                List<ChannelAuthorizeRegionTemp> channelAuthorizeRegionTempList = channelAuthorizeRegionService
                        .list(Wrappers.<ChannelAuthorizeRegionTemp>query().lambda()
                                .eq(ChannelAuthorizeRegionTemp::getChannelId, channelId)
                                .eq(ChannelAuthorizeRegionTemp::getBusinessType, businessType)
                        );
                if (channelAuthorizeRegionTempList.size() > 0) {
                    for (ChannelAuthorizeRegionTemp temp : channelAuthorizeRegionTempList) {
                        for (TsysAddressParam addressParam : list2) {
                            if (temp.getCode().equals(addressParam.getValue())) {
                                list.add(addressParam);
                            }
                        }
                    }
                }
            }
        }

        //返回数据
        List<TsysAddressParam> addressList = new ArrayList<>();
        list.forEach(addressParam -> {
            addressParam.setTitle(addressParam.getLabel());
            addressList.add(addressParam);
        });
        //默认查询层级最上层0层，表示全国区域
        int level = 0;
        List<TsysAddressParam> permissions = addressList.stream().filter(addressParam -> ParamConstants.ADDRESS_LEVEL.equals(addressParam.getAddrLevel())).collect(Collectors.toList());
        permissions.forEach(addressParam -> {
            findAddressParam(addressParam, addressList, level);
        });
        return new IResponse<List<TsysAddressParam>>().setData(permissions);

    }

    private void findAddressParam(TsysAddressParam addressParam, List<TsysAddressParam> tsysAddressParam, int level) {
        List<TsysAddressParam> children = tsysAddressParam
                .stream()
                .filter(child -> addressParam.getValue().equals(child.getUpperCode()))
                .collect(Collectors.toList());
        children.forEach(child -> {
            //层级+1
            child.setAddrLevel(level + 1 + "");
            findAddressParam(child, tsysAddressParam, level + 1);
        });
        addressParam.setChildren(children);
    }


    /**
     * 同步直营车商信息到案件服务公用方法
     */

    public void saveDirectCarDealerInfoToCase(Long carDealerId, DirectCarDealerCondition condition) {

        //收款账号
        List<ChannelReceivablesAccountTemp> accountTempList = channelAccountInfoService.list(Wrappers.<ChannelReceivablesAccountTemp>query().lambda()
                .eq(ChannelReceivablesAccountTemp::getChannelId, carDealerId));
        condition.setChannelAccountInfoList(accountTempList);

        //同步数据到案件服务
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("clientId", channelConfig.getCaseClientId());
        headers.put("clientSecret", channelConfig.getCaseClientSecret());
        Assert.isTrue((boolean) channelUseCaseService.saveDirectCarDealer(condition, headers).getData(), "操作失败,请重试!");
    }

    /**
     * 同步普通车商信息到案件服务公用方法
     */

    public void saveCommonCarDealerInfoToCase(CarDealerCondition condition) {
        //同步数据到案件服务
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("clientId", channelConfig.getCaseClientId());
        headers.put("clientSecret", channelConfig.getCaseClientSecret());
        // Assert.isTrue((boolean) channelUseCaseService.saveCommonCarDealer(condition, headers).getData(), "操作失败,请重试!");
        condition.setMqTypeEnum(MqTypeEnum.save_car);
        AfsTransEntity<CarDealerCondition> entity = senderChannelToCaseImpl.sendCommonCarDealerToCase(condition);
        senderChannelToCase.sendCommonCarDealerToCase(entity);
    }


    @GetMapping("/getAccountInfoByChannelId/{channelId}")
    @ApiOperation(value = "根据车商id查询收款账号信息是否完整")
    public IResponse getAccountInfoByChannelId(@PathVariable String channelId) {
        //查收款车商的业务类型
        DirectCarDealer carDealer = directCarDealerService.getById(channelId);
        String businessType = carDealer.getBusinessType();
        boolean newCar = businessType.contains(Constants.BUSINESS_TYPE_NEW_CAR);
        boolean oldCar = businessType.contains(Constants.BUSINESS_TYPE_OLD_CAR);
        //查车商的账户信息
        ArrayList<String> status = new ArrayList<>();
        status.add(ENABLED);
        String type = "channel";
        if (DIRECTCARDEALER.equals(carDealer.getChannelType())) {
            type = "carDealer";
            status.add(Constants.DRAFT);
        }
        //新车车款
        List<ChannelReceivablesAccountTemp> newCarCarMoneyAccount = channelAccountInfoService.list(Wrappers.<ChannelReceivablesAccountTemp>query().lambda()
                .eq(ChannelReceivablesAccountTemp::getChannelId, channelId)
                .eq(ChannelReceivablesAccountTemp::getAccountAttribute, Constants.BUSINESS_TYPE_NEW_CAR)
                .eq(ChannelReceivablesAccountTemp::getCollectionType, Constants.CAR_MONEY)
                .in(ChannelReceivablesAccountTemp::getStatus, status)
        );
        //新车佣金
        List<ChannelReceivablesAccountTemp> newCarCommissionAccount = channelAccountInfoService.list(Wrappers.<ChannelReceivablesAccountTemp>query().lambda()
                .eq(ChannelReceivablesAccountTemp::getChannelId, channelId)
                .eq(ChannelReceivablesAccountTemp::getAccountAttribute, Constants.BUSINESS_TYPE_NEW_CAR)
                .eq(ChannelReceivablesAccountTemp::getCollectionType, Constants.COMMISSION)
                .in(ChannelReceivablesAccountTemp::getStatus, status)
        );

        //二手车车款
        List<ChannelReceivablesAccountTemp> oldCarCarMoneyAccount = channelAccountInfoService.list(Wrappers.<ChannelReceivablesAccountTemp>query().lambda()
                .eq(ChannelReceivablesAccountTemp::getChannelId, channelId)
                .eq(ChannelReceivablesAccountTemp::getAccountAttribute, Constants.BUSINESS_TYPE_OLD_CAR)
                .eq(ChannelReceivablesAccountTemp::getCollectionType, Constants.CAR_MONEY)
                .in(ChannelReceivablesAccountTemp::getStatus, status)
        );
        //二手车佣金
        List<ChannelReceivablesAccountTemp> oldCarCommissionAccount = channelAccountInfoService.list(Wrappers.<ChannelReceivablesAccountTemp>query().lambda()
                .eq(ChannelReceivablesAccountTemp::getChannelId, channelId)
                .eq(ChannelReceivablesAccountTemp::getAccountAttribute, Constants.BUSINESS_TYPE_OLD_CAR)
                .eq(ChannelReceivablesAccountTemp::getCollectionType, Constants.COMMISSION)
                .in(ChannelReceivablesAccountTemp::getStatus, status)
        );
        //如果是新车,那就查新车的
        if (newCar) {
            if (newCarCarMoneyAccount.size() == 0) {
                if (type.equals("channel")) {
                    return IResponse.success("请录入新车车款账户!");
                }
                return IResponse.fail("请录入新车车款账户!");
            }
            if (newCarCommissionAccount.size() == 0) {
                if (type.equals("channel")) {
                    return IResponse.success("请录入新车佣金账户!");
                }
                return IResponse.fail("请录入新车佣金账户!");
            }
        }
        if (oldCar) {
            if (oldCarCarMoneyAccount.size() == 0) {
                if (type.equals("channel")) {
                    return IResponse.success("请录入二手车车款账户!");
                }
                return IResponse.fail("请录入二手车车款账户!");
            }
            if (oldCarCommissionAccount.size() == 0) {
                if (type.equals("channel")) {
                    return IResponse.success("请录入二手车佣金账户!");
                }
                return IResponse.fail("请录入二手车佣金账户!");
            }
        }
        return IResponse.success("账户校验成功");
    }


}
